2013-07-01 38 views
0

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

这里是我的jQuery代码:

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

凡我active类是改变链接的颜色的CSS样式。

我遇到的问题是每个链接都保持活动,如果我点击多个链接。我实际上只想让一个链接在点击时处于活动状态。我的jquery出了什么问题?谢谢!

+0

将真正帮助了解“何时”这个if语句火灾。可以给你几个不同的答案,否则 – SpYk3HH

回答

1

你就可以说

$(".testHeader a#"+thisID).toggleClass("active"); 
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'); 
    } 

}); 
+0

这可以工作,但菜单关闭时链接仍然有效。 –

+0

您使用什么操作和事件关闭菜单? –

+0

@JoseFuentes编辑与新的例子 –

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'); 
})