开发者

Nested lists - selecting path using Javascript

I have Javascript function that is adding css class "current" to selected link <a>. This function looks like that:

function markActiveLink() {
    var path = location.pathname;
    var links = null;
    if (path) {
        links = $("a[href^='" + path + "']");
    } else {
        links = $("a[href='/']");
    }
    links.parents("li").each(function () {
        $(this).addClass("current");
    });
} 

And I have nested list wchich looks similar to that list:

<ul class="menu">
    <li><a href="#a">menu item</a>
        <ul>
            <li><a href="#aa">menu item</a> </li>
            <li><a href="#ab">menu item</a></li>            
            <li><a href="#">menu item</a></li>
        </ul>
    </li>
        <li><a href="#a">menu item</a>
        <ul>
            <li><a href="#aa">menu item</a> </li>
            <li><a href="#ab">menu item</a></li>            
            <li><a href="#">menu item</a></li>
        </ul>
    </li>
</ul>

I want to add class "current" (using Javascript function) not to link <a> like it is now working but to <li> element and it's parent <li>. So it would look like that:

<ul class="menu">
    <li class="current"><a href="#a">menu item</a>
        <ul>
            <li><a开发者_JS百科 href="#aa">menu item</a> </li>
            <li class="current"><a href="#ab">menu item</a></li>            
            <li><a href="#">menu item</a></li>
        </ul>
    </li>
        <li><a href="#a">menu item</a>
        <ul>
            <li><a href="#aa">menu item</a> </li>
            <li><a href="#ab">menu item</a></li>            
            <li><a href="#">menu item</a></li>
        </ul>
    </li>
</ul>

Question: How can I modify my function markActiveLink() so that it would add class "current" both to <li> element and it's parent <li> element?

Any help here much appreciated!


Try:

links.parent().addClass('current')
     .closest('li').addClass('current');

jQuery Docs


Seems to me like it's working. I only changed the hrefs in your links so they wouldn't be duplicates and added some CSS to show the highlighted elements in this JSFiddle


Use the .parent() api to do it Docs EDIT Something like this:

$(this).parent().parent().addClass("current")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜