更改列表元素的活动类

时间:2013-10-27 13:58:18

标签: javascript jquery html

我正在尝试更改点击列表项的“活动”类,但我遗漏了一些东西。这是我的HTML和jquery的样子:

HTML

<ul class="additional-menu">
    <li class="active"><a href="link1"> Link1</a></li>
    <li><a href="javascript:void(0)" id="link2">Link2</a></li>
    <li><a href="javascript:void(0)" id="link3">Link3</a></li>
</ul>  

的jQuery

$("#link2").click(function(){

    if ($(this).find('#additional-menu li').hasClass('active')) {
        //console.log("Active class seen");
        $(this).find('#additional-menu li').removeClass('active');
        $(this).addClass('active');
    }
});

知道我错过了什么吗?我此时甚至都没有检测到活动课......

5 个答案:

答案 0 :(得分:9)

您可以将代码最小化为

$('.additional-menu').on('click','li', function(){
   $(this).addClass('active').siblings().removeClass('active');
});

http://jsfiddle.net/DvHBp/

演示

答案 1 :(得分:1)

代码中存在许多问题

//from what i can understand you need to change the active class to the clicked li element not just the link2 element
$("#link2").click(function(){

    // additional-menu is not an id it is a class and it is not a descendant of the li element 
    if ($(this).find('#additional-menu li').hasClass('active')) {
        //console.log("Active class seen");
        $(this).find('#additional-menu li').removeClass('active');
        //if you are using a if statement then addClass should be outside the if block
        $(this).addClass('active');
    }
});

jQuery(function(){
    var $lis = $('.additional-menu > li').click(function(){
        $lis.removeClass('active');
        $(this).addClass('active')    
    });
})

答案 2 :(得分:1)

find() get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element

你应该使用

$(this).parent().siblings('#additional-menu li')

因为在您的html结构#link2中,标签没有#additional-menu li的后代

答案 3 :(得分:1)

你可以做一些非常通用的东西:

<ul class="additional-menu">
    <li class="active"><a href="#l1"> Link1</a></li>
    <li><a href="#l2">Link2</a></li>
    <li><a href="#l3">Link3</a></li>
</ul>

使用此JavaScript:

$(function(){
    $('.additional-menu > li').click(function(){
        $('.additional-menu > li').removeClass('active');
        $(this).addClass('active');
    });
});

答案 4 :(得分:1)

尝试此解决方案:

<强> HTML:

<ul class="additional-menu">
    <li><a id="link1" href="link1"> Link1</a></li>
    <li><a href="javascript:void(0)" id="link2">Link2</a></li>
    <li><a href="javascript:void(0)" id="link3">Link3</a></li>
</ul>

<强> CSS:

.active{
    background-color : red;
}

<强> jQuery的:

//on first time load set the home menu item active
$(".additional-menu a#link1").addClass("active");

//on click remove active class from all li's and add it to the clicked li
$("a").click(function(){
   $("a").removeClass("active");
    $(this).addClass("active");
});

Demo