gpt4 book ai didi

javascript - 防止事件处理程序排队

转载 作者:行者123 更新时间:2023-11-29 18:28:11 24 4
gpt4 key购买 nike

我正在使用“One”连接点击处理程序。

Jquery 的“一个”方法将连接一个事件处理程序并在第一次调用后将其分离,但似乎如果您点击的速度足够快,可能会有多个事件处理程序排队并导致回调运行超过一次。

例如:

$("#button").one("click", function () {

//run logic

});

如何防止这种行为。我假设“一个”会在第一次运行后分离处理程序,但是如果您在它运行回调时单击按钮,假设它会运行第二次是否合理?

最佳答案

I am assuming "One" will detach the handler after running it the first time

不正确,.one 将在运行处理程序函数之前分离事件处理程序。如果你看.one源代码中,.off 在您的处理函数被调用之前被触发。

if (one === 1) {
origFn = fn;
fn = function (event) {
jQuery().off(event); //Your event is unregistered here
return origFn.apply(this, arguments); //Your handler is called
};
fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
}

正如 Frédéric Hamidi 在他的评论中指出的那样,

Even if the handler re-triggers the event during its execution, the actual handling of the new event will not occur until after the current handler has returned and the original event is fully resolved (possibly involving other handlers if the event is allowed to bubble up the DOM tree). By that time, the handler will have been removed in both cases.

证明: http://jsfiddle.net/skram/abcvW/2/

关于javascript - 防止事件处理程序排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985384/

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