gpt4 book ai didi

javascript - 如果已经绑定(bind)了事件处理程序,则不要绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 13:16:09 25 4
gpt4 key购买 nike

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

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' />

最佳答案

一种方法是使用 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' />

关于javascript - 如果已经绑定(bind)了事件处理程序,则不要绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com