我使用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' />
使用事件委派,以便您只需设置一次事件处理程序。 – Pointy