javascript 刷新页面后如何使 <li> 添加 css 类处于活动状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17295024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make <li> add css class active after refreshing page?
提问by loki
after clicking li
item. i set active
attribute to css class but li
has a link to forward another page. active css disappear? how to do this? i have been used localstorage to cache my old selected li item. i can not find any solution. How to make alive active class setting after refreshing? how to set active class alive after refreshing page?
点击li
项目后。我将active
属性设置为 css 类,但li
有一个链接可以转发另一个页面。活动css消失了?这个怎么做?我一直在使用 localstorage 来缓存我选择的旧 li 项目。我找不到任何解决方案。刷新后如何进行活动类设置?刷新页面后如何设置活动类?
<script type="text/javascript">
$(document).ready(function () {
$("li").click(function () {
var id = $(this).attr("id");
console.log(id);
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem != null) {
$('#' + selectedolditem).siblings().find("active").removeClass("active");
$('#' + selectedolditem).addClass("active");
localStorage.clear();
return;
}
$('#'+id).siblings().find("active").removeClass("active");
$('#' + id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
});
回答by MrCode
The problem with your code is you are trying to retrieve it onclick. That's the wrong logic. The correct logic is: when the page loads, retrieve it. When the li
is clicked, store it. You also have a problem when using find("active")
, you need to use the class character .
otherwise it will search for elements with the tag name active
not the class.
您的代码的问题是您试图在单击时检索它。那是错误的逻辑。正确的逻辑是:当页面加载时,检索它。当li
被点击时,其存储。使用时也有问题find("active")
,您需要使用类字符,.
否则它将搜索带有标签名称active
而不是类的元素。
$(document).ready(function () {
$("li").click(function () {
var id = $(this).attr("id");
$('#' + id).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem != null) {
$('#' + selectedolditem).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + selectedolditem).addClass("active");
}
});
回答by Hardik
Try following.
尝试跟随。
$('li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
回答by Rahman
Try following.
尝试跟随。
$(document).ready(function() {
$('.active').removeClass('active');
var currurl = window.location.pathname;
var val=$('li:has(a[href="'+currurl+'"])').addClass('active');
});