简体   繁体   English

Jquery - 从元素中删除类后仍然有效

[英]Jquery - Still active after removing class from element

I don't know if it's supposed to be like this, and I am doing something fundamentally wrong. 我不知道它是否应该像这样,我做的事情根本就是错误的。

I have a div with a given class and when you click on the div it gives a response, but then I have another div and when clicking on that one it removes the class from the first div . 我有一个给定类的div ,当你点击div它给出一个响应,但是我有另一个div ,当点击那个时,它从第一个div删除了该类。

However when I continue clicking on the first div after removing its class, I continue to get a response. 但是当我在删除课程后继续点击第一个div ,我会继续得到回复。

Why do the clicks continue to respond after I've removed the class? 在我删除课程后,为什么点击会继续响应?

HTML HTML

<div class="testing">Testing</div>

<div id="testing_remover">Remove class from testing</div>

JS: JS:

$(document).ready(function(){
    $('.testing').click(function(){
        console.log('testing is active');
    });

    $('#testing_remover').click(function(){
        $('.testing').removeClass('testing');
    });
});

Fiddle: http://jsfiddle.net/P3NpK/ 小提琴: http//jsfiddle.net/P3NpK/

Event handlers are bound to the element, not the selector. 事件处理程序绑定到元素,而不是选择器。

To remove a handler, use .off() : 要删除处理程序,请使用.off()

$(".testing").off("click");

Versions of jQuery earlier than 1.7 should preferably use .unbind instead of .off . jQuery的早于1.7版本最好.unbind代替.off

You'll have to either delegate the event handler higher up the DOM tree, or explicitly unbind the event handler. 您必须将事件处理程序委托给DOM树的更高位置,或者显式取消绑定事件处理程序。 Once the event is bound to an element, just changing the class name won't remove event handlers. 一旦事件绑定到元素,只更改类名将不会删除事件处理程序。

To remove the event handler ( updated fiddle ): 要删除事件处理程序( 更新小提琴 ):

$('#testing_remover').click(function(){
    $('.testing').off('click');
});

To delegate the event handler ( updated fiddle ): 委托事件处理程序( 更新小提琴 ):

$(document).on("click", ".testing", function(){
    console.log('testing is active');
});

The reason the delegation approach works is that jQuery captures the event once it's bubbled to the selected element (in this case, the document ). 委托方法起作用的原因是jQuery在冒泡到选定元素(在本例中为document )后捕获事件。 It checks to see if the event target matches the selector, and if so, executes the event handler. 它检查事件目标是否与选择器匹配,如果匹配,则执行事件处理程序。 If you've removed the class, the target will no longer match the selector. 如果您已删除该类,则目标将不再与选择器匹配。

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

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