开发者

Add a class to the parent li using jquery

I would like to add an "active" class to an li when clicked. The "active" class should also be present even when you click on a sub-page of that li.

For example:

<ul class="primarynav">
    <li id="first">
        <a href="#" id="link1" class=开发者_运维知识库"">link1</a>
        <ul class="megamenu" id="">
            <li class="column"><h4 class="special"><a href="#">sub-link</a</h4></li>
        </ul>
    </li>
    <li id="second">link2</li>
    <li id="third"><a href="#" id="link3" class="">link3</a>
        <ul class="megamenu" id="">
            <li class="column"><h4 class="special"><a href="#">sub-link3</a></h4></li>
        </ul>
    </li>
</ul>


perhaps something like this

$('.primarynav a').click(function() {
    // remove other links with 'active' class
    $('.primarynav a').removeClass('active');
    // set new 'active' link
    $(this).addClass('active');
});


If you want to target all the children, you can use the .children() method without any selector. This should work regardless of the complexity of the elements below the first <li>.

$("#primarynav li").children().click(function() {(this.addClass("active"))};

http://api.jquery.com/children/


Update

Take a look at this code below. It's also in a fiddle here: http://jsfiddle.net/rRkeJ/3/
It's basically the same idea as above but adapted more to what I think you want

$(".primarynav li").children().click(function() {
    $(".primarynav").children().removeClass("active");
    $(this).parent(".activable").addClass("active");
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜