Highlighting current page in the nav

此生再无相见时 提交于 2020-01-06 19:46:09

问题


I need to highlight the current page in my left nav.

The nav has to be loaded externally via an .shtml include:

<!--#include file="leftnav-menu.inc"-->

My urls take the form of:

www.xxx.com/mission-critical.shtml

but sometimes just:

www.xxx.com/energy.shtml (eg one word no hyphen)

My nav lists it as 'Mission critical'

How can I highlight the ul li with "class=selected"? I've seen something like this:

$(function(){
   var path = location.pathname.substring(1);
   if ( path )
     $('.leftmenuNav ul li a[@href$="' + path + '"]').attr('class', 'selected');
 });    

Can't quite get my head around the string splitting etc...

Sample nav bar:

<ul>
<li><a href="corporate-responsibility.shtml">Corporate responsibility</a></li>
<li><a href="overview.shtml">Overview</a></li>
<li><a href="governance.shtml">Governance</a></li>
<li><a href="our-approach.shtml">Our approach</a></li>
</ul>

回答1:


Okay, the jQuery syntax was slightly wrong. This should work:

$.ready(function()
{
   var path = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
   if ( path )
     $('.leftmenuNav ul li a[href="' + path + '"]').attr('class', 'selected');
});

Also, make sure the leftmenuNav is right (your code above doesn't show it)



来源:https://stackoverflow.com/questions/2206942/highlighting-current-page-in-the-nav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!