检查事件侦听器是否已经在侦听对象(以避免重复操作) [英] Check if an event listener is already listenning to an object (to avoid duplicate actions)
问题描述
我的页面如下:
<a class="myClass">1</a>
<a class="myClass">2</a>
<a class="myClass">3</a>
<a class"add_anchor">Add Anchor</a>
页面完全加载后,我将侦听器绑定到执行特定功能f
的a.myClass
.
When the page is fully loaded, I bind a listener to a.myClass
that executes a certain function f
.
单击Add Anchor
会通过AJAX将新的a.myClass
添加到列表中.因此,要监听所有a.myClass
(新添加的和初始的),我应该两次调用监听器,总体代码如下:
The click on Add Anchor
adds via AJAX a new a.myClass
to the list. So, to listen to all a.myClass
s (the newly added and the initial ones), I should call the listener twice, the overall code looks like:
function listenToMyClassClick{
$('.myClass').click(function(e){
e.preventDefault();
f();
});
}
listenToMyClassClick();
$('.addAnchor').click(function(e){
$.ajax({
type: "POST",
url: url,
cache: false,
success: function(data){
listenToMyClassClick();
}
});
});
结果,f
被执行两次.我该如何使用jQuery检查某个侦听器已在执行,以便下次不再执行它?
As a result, f
is executed two times. How can I check with jQuery that a listener is already executing so that I don't execute it another time?
谢谢您的帮助.
推荐答案
创建一个委托事件,如Sergiu建议的那样.与其将click事件绑定到元素的动态列表中存在的元素,不如将click事件绑定到该元素的父元素,即使您单击其子元素,该事件仍会引发click事件.这称为事件冒泡.这是显示如何使用jQuery的代码片段:
Create a delegated event, like Sergiu suggests. Instead of binding a click event to an element that exists in a dynamic list of elements, bind a click event to the element's parent, which will still raise a click event even when you click one its children. This is called event bubbling. Here's a snippet of code showing how to do it using jQuery:
// Attach a delegated event handler
$( "#list" ).on( "click", "a", function( event ) {
f();
});
您将click事件直接绑定到作为父项的"#List"上,并告诉它专门侦听第二个参数中定义的"a"元素中的事件.
You bind the click event directly to "#List", being the parent and tell it to specifically listen for events from "a" elements, which is defined in the second parameter.
这篇关于检查事件侦听器是否已经在侦听对象(以避免重复操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!