[英]Jquery - Still active after removing class from element
我不知道它是否应该像这样,我做的事情根本就是错误的。
我有一个给定类的div
,当你点击div
它给出一个响应,但是我有另一个div
,当点击那个时,它从第一个div
删除了该类。
但是当我在删除课程后继续点击第一个div
,我会继续得到回复。
在我删除课程后,为什么点击会继续响应?
HTML
<div class="testing">Testing</div>
<div id="testing_remover">Remove class from testing</div>
JS:
$(document).ready(function(){
$('.testing').click(function(){
console.log('testing is active');
});
$('#testing_remover').click(function(){
$('.testing').removeClass('testing');
});
});
小提琴: http : //jsfiddle.net/P3NpK/
您必须将事件处理程序委托给DOM树的更高位置,或者显式取消绑定事件处理程序。 一旦事件绑定到元素,只更改类名将不会删除事件处理程序。
要删除事件处理程序( 更新小提琴 ):
$('#testing_remover').click(function(){
$('.testing').off('click');
});
委托事件处理程序( 更新小提琴 ):
$(document).on("click", ".testing", function(){
console.log('testing is active');
});
委托方法起作用的原因是jQuery在冒泡到选定元素(在本例中为document
)后捕获事件。 它检查事件目标是否与选择器匹配,如果匹配,则执行事件处理程序。 如果您已删除该类,则目标将不再与选择器匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.