开发者

jquery navigation highlight

Hi I am trying to write a script in Jquery that auto selects the current page link in the main nav. The nav is just a simple UL like this:

<ul id="primaryNav">
    <li>
        <a href="retail.html">Home</a>
    </li>
    <li>
        <a href="vision.html">Our Vision</a>
    </li>
    <li>
        &开发者_如何学编程lt;a href="context.html">Town in context</a>
    </li>
</ul>

My Jquery so far looks like this:

$('#primaryNav').find("a[href='"+window.location.href+"']").each(function(){
    $(this).addClass("selected");
}); 

This doesn't work because I think its selecting the whole URL whereas I just need it to select the last part e.g retail.html or vision.html then add the class .selected

Can anyone please help? Thanks in advance.


Use an attribute ends-with selector to be safe here instead ($= instead of =), like this:

$('#primaryNav').find("a[href$='"+window.location.href.split('/').pop()+"']")
                .addClass("selected");

Also no need for a .each() here, just calling .addClass() will add it to all matched elements (even though there should be one for your example).


Like that (basing on page name too):

$('#primaryNav').find("a[href$='" + window.location.href.split("/").reverse()[0] + "']").addClass("selected");


What about a simple substring?

var href = window.location.href;
var htmlPageName = href.substring(href.lastIndexOf('/') + 1);

$('#primaryNav').find("a[href='" + htmlPageName +"']").each(function(){
    $(this).addClass("selected");
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜