Jquery添加类并在页面重新加载时保留
我有一个简单的导航菜单。 主页链接有一个下拉活动类。 我需要这样做:当用户按下例如文章链接时,jquery必须从Home中删除下拉活动类并将此类设置为选定的链接。 我知道我可以使用removeClass和addClass,但是当重新加载页面时我需要保留选定的链接类。 我听说过cookies和localstorage来设置课程,但我不知道怎么做。 有人能帮我吗?
你可以用这种方式使用jquery:
$(document).ready(function(){ if($(".dropdown a").attr("href")==window.location.href){ $(".dropdown").attr("class","dropdown active"); } else{ $(".dropdown").attr("class","dropdown"); } });
只需检查一次是否有任何错误,这应该可以解决您的问题。
$('.nav li').click(function(){ $('.navt li').removeClass('active'); $(this).addClass('active'); });
或使用cookie(理想情况下不是很好的选择)
set_page.php
setcookie(’nav’,’put-the-li-classname-here’,time(),’/’);
receive_page.php
$ getnav = $ _COOKIE [‘nav’];
JS
var variable1 = //在这里获取php val;
$(document).ready(function(){ $('.navt li').removeClass('active'); $('.'+variable1).addClass('active');
});
我能够在一个简单的HTML网站上工作。
下面的函数将检查用户或访问者正在查看的页面URL,并与菜单项上的页面进行比较。 如果它们匹配,它会将.active
类添加到该菜单项。
考虑您自己的HTML结构,请尝试以下操作:
// Navigation Markup, let's add an id for easy targeting.
// The JS jQuery(function() { var pgurl = window.location.href.substr(window.location.href .lastIndexOf("/")+1); jQuery("#nav ul li a").each(function(){ if(jQuery(this).attr("href") == pgurl || jQuery(this).attr("href") == '' ) jQuery(this).addClass("active"); }) });
注意:该函数以
元素,稍微更改一下该函数。
什么对我有用:
$(document).ready(function() { const regex = /http:\/\/.*\/(.*)\//g; const match = regex.exec(window.location.href); // iterate over all and find match if (match) { $(".nav-link").each(function() { if ($(this).attr("href").slice(1) == match[1]) { $(this).addClass("active"); } }); } // set active first element else { $(".nav-link:first").addClass("active"); } });
这应该有所帮助。 添加.each
@Ahosan Karim Asik解决方案。
$(document).ready(function(){ $(".dropdown a").each(function(){ if($(".dropdown a").attr("href")==window.location.href){ $(".dropdown").attr("class","dropdown active"); } else{ $(".dropdown").attr("class","dropdown"); } }); });