addClass / removeClass無法正常工作

[英]addClass/removeClass are not working properly


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/

http://jsfiddle.net/k4605e3z/

3 个解决方案

#1


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

的jsfiddle

#2


1  

Simply change this :

只需改變這個:

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

#3


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

Fiddle

小提琴


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/11/19/3166f90c7c4b76e09b888935278e7a50.html



 
  © 2014-2022 ITdaan.com 联系我们: