gpt4 book ai didi

javascript - 如何仅在 jquery on() 函数不存在时设置它?

转载 作者:行者123 更新时间:2023-11-30 07:33:12 24 4
gpt4 key购买 nike

我通过 ajax 调用附加内容,我在其中添加了一个 jquery on()单击事件的函数。每次我更新内容时,事件也会再次设置,所以最后它会被执行几次。我怎样才能避免这种行为?

如何测试文档是否已经设置了点击事件?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="open-alert">Click</a>
<script>
// first ajax load
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});

// second ajax load
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
</script>

我已经尝试只使用 jQuery.isFunction() ,但我不明白如何在这种情况下应用它。

最佳答案

如果多次执行,可以解绑点击事件。

$(document).unbind('click').on("click", ".open-alert", function () {
//do stuff here
});

或者你也可以使用它

$(document).off("click", ".open-alert").on("click", ".open-alert", function () { 

});

关于javascript - 如何仅在 jquery on() 函数不存在时设置它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43885339/

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