gpt4 book ai didi

jquery - 遍历导航标签并停留在其中之一

转载 作者:行者123 更新时间:2023-12-01 03:59:35 25 4
gpt4 key购买 nike

我使用 bootstrap 3.3.7 编写了一个导航选项卡

<ul class="nav nav-tabs nav-justified">
<li><a href="#">Concept</a></li>
<li><a href="#">Code</a></li>
<li ><a href="#">Read</a></li>
<li><a href="#">Action</a></li>
</ul>

每次我单击一个选项卡时,它都会被激活,而其他选项卡则会被停用,

<script>
$(document).ready(
$(".nav-tabs li").on("click", function(){
$(".nav-tabs li").removeClass("active");
$(this).addClass("active");
}));
</script>

它可以很好地使用代码,

enter image description here

但是,当我刷新页面时,所有标签active类都被删除了,

我希望它保留在点击的标签上,直到触发另一次点击。

最佳答案

您正在做的是在客户端。他们并没有坚持下去。使用 localStorage 或 Cookie 来实现持久状态,即使在页面重新加载后也是如此。

此外,下面的代码将无法工作并抛出错误。 更正后的代码是:

$(document).ready(function() {
$(".nav-tabs li").on("click", function() {
$(".nav-tabs li").removeClass("active");
$(this).addClass("active");
});
});

因此每次发生点击事件时,设置localStorage:

$(document).ready(function() {
$(".nav-tabs li").on("click", function() {
$(".nav-tabs li").removeClass("active");
$(this).addClass("active");
localStorage.setItem("active", $(this).text().trim());
});
});

当您加载页面时,设置active:

$(document).ready(function() {
$(".nav-tabs li").each(function () {
if (typeof localStorage.getItem("active") != "undefined" && $(this).text().trim() == localStorage.getItem("active"))
$(this).addClass("active");
});
$(".nav-tabs li").on("click", function() {
$(".nav-tabs li").removeClass("active");
$(this).addClass("active");
localStorage.setItem("active", $(this).text().trim());
});
});

片段

$(document).ready(function() {
$(".nav-tabs li").each(function() {
if (typeof localStorage.getItem("active") != "undefined" && $(this).text().trim() == localStorage.getItem("active"))
$(this).addClass("active");
});
$(".nav-tabs li").on("click", function() {
$(".nav-tabs li").removeClass("active");
$(this).addClass("active");
localStorage.setItem("active", $(this).text().trim());
});
});
.active {font-weight: bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav nav-tabs nav-justified">
<li><a href="#">Concept</a></li>
<li><a href="#">Code</a></li>
<li><a href="#">Read</a></li>
<li><a href="#">Action</a></li>
</ul>

注意: StackSnippets 不允许 localStorage。请检查输出:JSBin .

关于jquery - 遍历导航标签并停留在其中之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com