Sorry for the noobish question.
I've got a menu similar to this:
<div id="navigation">
<ul>
<li><a href="url">menu item</a></li>
<li><a href="url">menu item</a>
<ul>
<li><a href="url">sub menu item</a></li>
<li><a href="url">sub menu item</a>
<ul>
<li><a href="url">sub sub menu item</a></li>
<li><a href="url">sub sub menu item</a></li>
<li><a href="url">sub sub menu item</a></li>
</ul>
</li>
<li><a href="url">sub menu item</a></li>
<li><a href="url">sub menu item</a></li>
</ul>
</li>
<l开发者_运维百科i><a href="url">menu item</a></li>
<li><a href="url">menu item</a></li>
</ul>
</div>
I'm trying to change the class for the selected page. I'm part way there with this:
$(function(){
var path = location.pathname.substring(1);
if ( path ){
$('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
}
});
Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.
Would appreciate any help at all.
Thanks,
Andy.
You can use .parents()
and :last
(since they're returned in the order found...top parent is last) when looking for the <li>
, like this:
$('#navigation a[href$="' + path + '"]').parents('li:last').addClass('selected');
Also .addClass()
is probably what you're after here :)
$('#navigation>ul>li:has(a[href$="' + path + '"])')
use >
$('#navigation > ul > li > a[href$="' + path + '"]')
精彩评论