简体   繁体   English

使用jQuery将类添加到父级li

[英]Add a class to the parent li using jquery

I would like to add an "active" class to an li when clicked. 单击后,我想向li添加一个“活动”类。 The "active" class should also be present even when you click on a sub-page of that li. 即使单击该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. 如果要定位所有子项 ,则可以使用.children()方法而不使用任何选择器。 This should work regardless of the complexity of the elements below the first <li> . 无论第一个<li>下面的元素的复杂性如何,这都应该起作用。

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

http://api.jquery.com/children/ 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/ 它也在这里摆弄: 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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM