2016-06-21 73 views
0

我使用ajax调用某些窗体,然后绑定每个按钮的事件处理程序。问题是......当我使用ajax调用一个新的表单时,再次为新元素调用事件处理程序,然后为之前的元素添加两次。我如何检测一个事件处理程序是否已经在一个元素上,而不是再次绑定它?如果绑定事件处理程序已绑定

function x(){ 
    $("input:button").click(function(){ 
     alert('is this called once?'); 
    }); 
} 

<input type='button' value='Disable me' /> 
<input type='button' value='Disable me' /> 

function x(){ 
 
    $("input:button").click(function(){ 
 
     alert('is this called once?'); 
 
    }); 
 
} 
 

 
// calling event twice simulating an ajax calling: 
 
x(); 
 
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type='button' value='Disable me' /> 
 
<input type='button' value='Disable me' />
做到这一点

+3

使用事件委派,以便您只需设置一次事件处理程序。 – Pointy

回答

2

是否单击处理程序实际上需要重新添加每次你的AJAX请求被调用时?如果不考虑修改像这样的代码:

//Only call this once; new buttons will still trigger it 
 
$(document).on('click', 'input:button', function() { 
 
    alert('is this called once?'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='button' value='Disable me' /> 
 
<input type='button' value='Disable me' />

通过处理程序连接到文件并提供一个选择器('input:button'),功能按钮上点击时才会触发,可自动将应用于初始绑定后添加的任何新按钮。

+0

这两个答案,这一个和A.J之一,工作,我不知道至少有一个标记作为答案,我要去标记这个,因为@Mike McCaughan警告要移除所有事件处理程序。感谢你们! – stramin

2

一种方法是使用jQuery的off函数删除附加任何事件,然后将其固定。

这是确保只有一个点击事件附加到元素。

示例代码段:

function x() { 
 
    $("input:button").off('click').on('click', function() { 
 
    console.log('is this called once?'); 
 
    }); 
 
} 
 

 
// calling event twice simulating an ajax calling: 
 
x(); 
 
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='button' value='Disable me' /> 
 
<input type='button' value='Disable me' />

+1

有一点需要注意。使用'off'('click')'将删除选择器所匹配元素上的所有*单击事件处理程序。因此,如果你在'x'函数之外附加一个事件处理函数,那些函数也将被删除。有一个'off'的重载需要一个函数,该函数是要移除的处理程序,但这需要使用处理程序的命名函数。 –

+0

我也应该注意到,这个答案没有什么错,只是在使用'off'时要记住一些事情。 –

相关问题