jquery 添加删除类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2245934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery add remove class
提问by mtwallet
I have 4 anchors, I want to add a class of current to an anchor as it is clicked and remove the class from the other 3 at the same time. Here's my code. what am I doing wrong?
我有 4 个锚点,我想在单击时向锚点添加一类电流,并同时从其他 3 个锚点中删除该类。这是我的代码。我究竟做错了什么?
if ($("ul#thumb a").hasClass("current") {
$("ul#thumb a").removeClass("current");
$(this).addClass("current");
});
and my html looks like this:
我的 html 看起来像这样:
<ul id="thumbs">
<li>
<!-- intro page navi button -->
<a id="t0" class="active" name="t0">The Company</a>
<ul class="navi">
<li><a style="display:none"></a></li>
<li><a id="t1" name="t1">The Brief</a></li>
<li><a id="t2" name="t2">The Solution</a></li>
<li><a id="t3" name="t3">The Result</a></li>
</ul>
</li>
</ul>
回答by Sampson
By using event-delegation, we only bind one handler for all click events. When an anchor (other than the .current
anchor) is clicked, we strip the .current
anchor of its class, and make the clicked anchor the new current one:
通过使用事件委托,我们只为所有点击事件绑定一个处理程序。当一个锚点(除了.current
锚点)被点击时,我们剥离.current
其类的锚点,并使被点击的锚点成为新的当前锚点:
$("#thumbs").on("click", "a:not(.current)", function ( event ) {
$(".current", event.delegateTarget).removeClass("current");
$(this).addClass("current");
});
回答by Raghvendra
I think this will help you
我想这会帮助你
$("a").click(function() {
$('a').removeClass('current');
var id = $(this).attr('id');
$('#'+id).addClass('current');
});