简体   繁体   English

切换类时,jQuery on()不起作用

[英]jQuery on() doesn't work when switching classes

[edit] THIS CODE DOES WORK [编辑] 此代码有效

Found out had multiple on() handlers on the same event/class. 发现在同一事件/类上有多个on()处理函数。 [/edit] [/编辑]

I'm using the following code: 我正在使用以下代码:

$selector.on('click', '.heya', function($e){
     alert('heya');
     jQuery(this).attr('class', 'byebye');
});


$selector.on('click', '.byebye', function($e){
     alert('byebye');
     jQuery(this).attr('class', 'heya');
});

Now clicking one of the elements once works correctly, but when clicking it again both callbacks are called. 现在,单击其中一个元素一次即可正常工作,但是再次单击时,将调用两个回调。 Somehow the previous "on()" trigger did not get removed. 不知何故,先前的“ on()”触发器没有被删除。 Anyone knows why? 有人知道为什么吗? I know I can solve this issue differently, but this would be the cleanest solution... 我知道我可以用不同的方式解决这个问题,但这将是最干净的解决方案...

Use addClass and removeClass methods instead. 请改用addClassremoveClass方法。

$selector.on('click', '.heya', function($e){
     alert('heya');
     $(this).removeClass("heya").addClass("byebye");
});

$selector.on('click', '.byebye', function($e){
     alert('byebye');
     $(this).removeClass("byebye").addClass("heya");
});

Try this this will help you to solve your problem. 尝试此操作将帮助您解决问题。

$(".heya").on('click', function($e){
     alert('heya');
     $(this).attr('class', 'byebye');
});


$(".byebye").on('click', function($e){
     alert('byebye');
     $(this).attr('class', 'heya');
});

Try this code: 试试这个代码:

$(".heya,.byebye").on('click', function($e){

     $(this).toggleClass('byebye heya');

});

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM