简体   繁体   English

从HTML中删除用作选择器的类或ID后,为什么仍要调用jQuery函数?

[英]Why is a jQuery function still called once the class or id used as the selector has been removed from the HTML?

http://jsfiddle.net/q98G6/ http://jsfiddle.net/q98G6/

HTML 的HTML

<p>[QUESTION]</p>
<div class="answer-notdone">
    <p>[CONTENT_1]</p>
</div

<div class="answer-notdone">
    <p>[CONTENT_2]</p>
</div

<div class="answer-notdone">
    <p>[CONTENT_3]</p>
</div

JavaScript 的JavaScript

$(".answer-notdone").click(function(){
    markQuestion(this); //external function 
    $(".answer-notdone").addClass('answer-complete').removeClass('answer-notdone');
)};

The example above is for a multiple choice question in a quiz - the user should only be able to click the answer once, and then it should be 'unlinked' from that jQuery function. 上面的示例针对测验中的多项选择题-用户应该只能单击一次答案,然后应与该jQuery函数“取消链接”。

But the problem is even after the class has been removed successfully, the jQuery function is still called when clicked. 但问题是,即使已成功删除该类后,单击时仍会调用jQuery函数。 Why? 为什么?

Here is a fiddle I made of a demo, if the code above was not clear: http://jsfiddle.net/q98G6/ 如果上面的代码不清楚,这是我制作的一个小提琴: http : //jsfiddle.net/q98G6/

The selector is only used to find the elements, once the element is found and the event handler is attached to it, the selector does not have any relevance because the handlers are attached to the element not to the selector. 选择器仅用于查找元素,一旦找到元素并将事件处理程序附加到该选择器,该选择器就没有任何关联,因为处理程序附加到该元素而不是选择器。

One way to solve the problem is to make use event delegation . 解决问题的一种方法是使用事件委托 In event delegation the handlers are attached to an ancestor element and we pass a selector as a target element. 在事件委托中,处理程序将附加到祖先元素,然后将选择器作为目标元素传递。 In this method the target selector is evaluated lazily. 在这种方法中,目标选择器是延迟计算的。

$(document).on('click', ".answer-notdone", function(){
    markQuestion(this); //external function 
    $(".answer-notdone").addClass('answer-complete').removeClass('answer-notdone');
)};

The selector returns all the elements that match it at the time you bind the handler, and then it attaches the handler to all those elements. 选择器将在绑定处理程序时返回与其匹配的所有元素,然后将处理程序附加到所有这些元素上。 Changing an element's class later does not remove the event handlers that were already bound. 以后更改元素的类不会删除已绑定的事件处理程序。

If you want your handler to be bound to dynamically changing elements, you should use delegation: 如果希望将处理程序绑定到动态更改的元素,则应使用委托:

$(document).on('click', '.answer-notdone', function() {
    ...
});

Try this 尝试这个

$(document).on('click',".answer-notdone",function () {
     //markQuestion(this);
     $(".answer-notdone").addClass('answer-complete').removeClass('answer-notdone');
});

FIDDLE DEMO 现场演示

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

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