如何使用jQuery或JavaScript基于当前URL和单击事件将一个类“active”分配给li元素
我正在尝试创建一个菜单,只要选择并加载了一个类“active”就会被分配给该页面。 现在它默认仅应用于索引页面。
我的菜单片段:
试试这个代码。 它在我的工作。
我假设如果你使用php你的页面就像这样。 只需在每个页面中定义一个$ active变量。
然后你的HTML将是这样的。
我认为这会更好: –
$(".navbar-nav").children("a").click(function(){ $(".navbar-nav").children("li").removeClass("active"); $(this).parent("li").addClass("active"); })
我希望如果您可以编辑主题,这将对您有所帮助。
$slug = basename(get_permalink());
可能有其他方式来获取当前页面的url或标题或ID,请在此处查看链接
你可以用PHP做到这一点。
脚步:
1)创建一个多维菜单数组。
2)Key是链接,值是文本。
3)获取当前页面URL。
4)使用
basename()
获取url的最后一段。5)这将是您当前的页面变量。 如果为空,请将其指定给主页。
6)循环
menus
数组。7)循环显示菜单。
8)如果当前循环项等于当前页面,则添加class
active
else,不添加任何类。
我想你正在寻找这个。 尝试和测试 ,参见演示和更新演示
$(".navbar-nav").find("a").click(function(){ $(".navbar-nav").find("li").removeClass("active"); $(this).parent("li").addClass("active"); }) $( window ).load(function() { var which_page=window.location.href.substr(window.location.href .lastIndexOf("/")+1); $(".navbar-nav").find("a").each(function(){ if($(this).attr("href") == which_page) { $(this).addClass("active"); } }) });
更新的演示
试试这个jQuery: –
$("div.navbar-nav").on('click', 'li', function() { $(this).siblings().removeClass('active'); $(this).addClass('active'); });
如果要在页面加载后根据锚标记url保留最后选择的值,则还要添加此行。
// get the actual pathname: var path = location.pathname; // filter menu items to find one that has anchor tag with matching href: $('.navbar-nav li').filter(function(){ return '/' + $('a', this).attr('href') === path; // add class active to the item: }).addClass('active');
要么
$(document).ready(function () { var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1"); $('.navbar-nav a').each(function () { if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase()) $(this).parent().addClass('active'); }); });
希望它能帮到你:)