0

例如,如果我有一个下拉导航,我希望活动链接的颜色与导航链接的其余部分不同。类似于:http ://www.emerson.edu/ 。

这是我的jQuery代码:

if ($(".testHeader a#" + thisID).hasClass("active")) {
    $(".testHeader a").removeClass("active");
} else {
    $(".testHeader a").removeClass("active");
    $(".testHeader a#" + thisID).addClass("active");
}

我的active课程是改变链接颜色的css样式。

我遇到的问题是,如果我点击超过 1 个链接,每个链接都会保持活动状态。我实际上只希望一个链接在被点击时处于活动状态。我的 jquery 怎么了?谢谢!

4

3 回答 3

1

你可以说

$(".testHeader a#"+thisID).toggleClass("active");
于 2013-07-01T17:22:20.040 回答
0

使用this. 首先在触发事件时删除所有活动类,然后将类添加到当前选定的对象上,this.

$('a').click(function(){
    $('a').removeClass('active');
    $(this).addClass('active');
});

编辑:要通过再次单击来关闭它,请执行此操作。

$('a').click(function(){
     if($(this).hasClass('active')){
         $(this).removeClass('active');
     }else{
         $('a').removeClass('active');
         $(this).addClass('active');
     }

});
于 2013-07-01T17:26:36.847 回答
0

了解这发生在什么“事件”上会有所帮助。

如果是hover事件。然后你可以做类似的事情:

$('.testHeader a').hover(function(e) { $(this).toggleClass('active'); });

//  However, if any of your links are dynamic or a half dozen other issues, this could misfire
//  Thus I would really suggest the long form as:

$(document).on('mouseenter', '.testHeader a', function(e) {
    $(this).addClass('active');
})
.on('mouseleave', '.testHeader a', function(e) {
    $(this).removeClass('active');
})

如果在click活动中,那么您可以执行以下操作:

$(document).on('click', '.testHeader a', function(e) {
    $('.testHeader .active').removeClass('active');
    $(this).addClass('active');
})
于 2013-07-01T17:33:01.833 回答