4

我正在尝试更改单击列表项的“活动”类,但我遗漏了一些东西。这是我的 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');
    }
});

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

4

5 回答 5

10

您可以将代码最小化为

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

演示在http://jsfiddle.net/DvHBp/

于 2013-10-27T14:07:21.620 回答
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')    
    });
})
于 2013-10-27T14:00:15.440 回答
1

查找() 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

于 2013-10-27T14:02:23.357 回答
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');
    });
});
于 2013-10-27T14:03:03.743 回答
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");
});

演示

于 2013-10-27T14:09:55.907 回答