I have 5 button each of them have the class .leg, I want when the user clicks on one of them to add 'active' on the class attribute and remove it from every other, so I have:
我有5个按钮,每个按钮都有类.leg,我想当用户点击其中一个在class属性上添加'active'并将其从其他属性中删除时,我想:
j$(".leg").on "click", (event)->
j$('.leg').removeClass('active')
j$(event.target).addClass('active')
Sometimes when I click on one of the button the 'active' class is not added. I suspect that the removeClass has not finish its execution, 'active' is added and then removed again. Since the removeClass
does not have a callback is there any other way to fix this issue?
有时当我点击其中一个按钮时,不会添加“活动”类。我怀疑removeClass还没有完成执行,添加'active'然后再次删除。由于removeClass没有回调,还有其他方法可以解决这个问题吗?
http://jsfiddle.net/k4605e3z/
3
Use $(this)
instead of $(e.target)
:
使用$(this)而不是$(e.target):
$('.leg').click(function(event){
$('.leg').removeClass('active');
$(this).addClass('active');
});
this
is the dom element selected when you added the click handler.
这是添加单击处理程序时选择的dom元素。
的jsfiddle
1
Simply change this :
只需改变这个:
$('.leg').click(function(event){
$('.leg').removeClass('active');
$(this).addClass('active');
});
0
You have an element inside .leg
so when you click, the target is the span
. You can get the parent by this event.target.parentElement
你有一个.leg元素,所以当你点击时,目标就是跨度。您可以通过此event.target.parentElement获取父级
$('.leg').click(function(event){
$('.leg').removeClass('active');
$(event.target.parentElement).addClass('active')
})
小提琴
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/11/19/3166f90c7c4b76e09b888935278e7a50.html。