gpt4 book ai didi

javascript - 从 html 元素动态添加和删除事件监听器

转载 作者:行者123 更新时间:2023-12-03 02:12:13 25 4
gpt4 key购买 nike

我有可编辑的 html 页面,以便用户可以复制和粘贴 html 元素,也可以动态创建元素。我已经在这些元素中 Hook 了一些事件监听器,但显然我需要在这些动态添加的元素中 Hook 事件监听器。我想出的解决方案是,每次用户关注这些元素时,都会触发事件并将所需的事件监听器与该特定元素连接起来。

$('body').on('focusin', '.propclass', function() {
autocomplete(this,idsprop);
});

一切都工作正常,除了每次我 Hook 事件监听器时,它不会丢弃前一个事件监听器,而是为该元素添加一个事件监听器,例如,如果我在该元素上聚焦 5 次,它就会钩住该元素并调用 5 次。

我尝试通过以下方式删除以前的事件监听器:

inp.removeEventListener("input",call_input,true);

但是没有成功。

function autocomplete(inp, arr) {
inp.removeEventListener("input",call_input,true);
inp.removeEventListener("keydown",call_keydown,true);


inp.addEventListener("input", function(e) {
call_input(e);
});

inp.addEventListener("keydown", function(e) {
call_keydown(e);
});

};

因此,每次 autocomplete 调用时,我首先尝试删除监听器,然后添加新的监听器。

有什么方法可以删除以前的事件监听器吗?我的方法是正确的还是有更好的方法来做到这一点?

最佳答案

您必须保存对作为参数传递给 addEventListener 的先前函数的准确引用。 。例如:

let inputListener;
let keydownListener;
function autocomplete(inp, arr) {
// use the listeners that were assigned on the previous running of this function:
inp.removeEventListener("input", inputListener, true);
inp.removeEventListener("keydown", keydownListener, true);
// assign new listeners to the outer variables so they can be referenced the next time:
inputListener = e => call_input(e);
keydownListener = e => call_keydown(e);
inp.addEventListener("input", inputListener);
inp.addEventListener("keydown", keydownListener);
}

那就是您是否有机会在监听器中添加更多内容。如果听众只是 call_input(e)call_keydown(e) ,然后传递call_inputcall_keydown直接:

function autocomplete(inp, arr) {
inp.removeEventListener("input",call_input,true);
inp.removeEventListener("keydown",call_keydown,true);
inp.addEventListener("input", call_input);
inp.addEventListener("keydown", call_keydown);
}

如果您最初使用未在其他地方引用的匿名函数,您将无法通过removeEventListener 将其删除。

关于javascript - 从 html 元素动态添加和删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49504944/

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