简体   繁体   English

突出显示主菜单上的当前页面

[英]Highlight current page on main menu

I'm trying to use javascript / jQuery to highlight the current pages list item on my main menu. 我正在尝试使用javascript / jQuery突出显示主菜单上的当前页面列表项。 I am new to scripting and can't work out what the problem is. 我是脚本新手,无法解决问题所在。 Here is the code i've been trying with. 这是我一直在尝试的代码。

<ul id="#mainMenu">
    <li><a href="/home">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>

<script type="text/javascript">
$('#mainMenu li a').on('click', function(){
    $('li a.active').removeClass('active');
    $(this).addClass('active');
});
</script>

If you're happy to add the class to the menu based on the current URL in oppose to using the .click function then I have a solution for you. 如果你很乐意根据当前的URL将类添加到菜单中,而不是使用.click函数,那么我有一个解决方案。

$(document).ready(function(){
    $("a[href*='" + location.pathname + "']").addClass("active");
});

On page load. 在页面加载。 This compares all the anchor tags on the page to the current URL. 这会将页面上的所有锚标记与当前URL进行比较。 And if they match. 如果他们匹配。 Adds the class of .active to the element. .active类添加到元素中。

I want to add to the accepted answer by Jay. 我想补充杰伊接受的答案。 Sometimes your URL may be 'posts' for a menu item and 'posts/create' for another one. 有时,您的URL可能是菜单项的“帖子”,另一个是“发布/创建”。 So code from accepted answer will highlight both. 因此,接受答案的代码将突出显示两者。 To avoid that, do the following: use window.location.href instead of location.pathname and remove * after href: 要避免这种情况,请执行以下操作:使用window.location.href而不是location.pathname并在href之后删除*:

$(document).ready(function(){
    $("a[href='" + window.location.href + "']").addClass("active");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM