【问题标题】:Dynamically add and remove event listener from html element从 html 元素中动态添加和删除事件监听器
【发布时间】:2018-03-27 05:23:26
【问题描述】:

我有可编辑的 html 页面,因此用户可以复制和粘贴 html 元素,也可以动态创建元素。我在这些元素中挂钩了一些事件侦听器,但显然我需要在这些动态添加的元素中挂钩事件侦听器。我想出的解决方案是,每次用户关注这些元素时,都会触发一个事件,并且所需的事件侦听器与该特定元素挂钩。

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

一切都很好,除了每次我挂钩事件侦听器时,它不会丢弃以前的事件侦听器,而是为该元素添加一个事件侦听器,例如,如果我在该元素上关注 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 调用时,我首先尝试删除监听器然后添加新监听器。

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

【问题讨论】:

  • 所以,最终@CertainPerformance 答案是您正在寻找的答案。一旦他注意到您的更新,他可能会根据您的用例对其进行定制。如果您测试它并且它有效,请记住选择他的答案以奖励他并将其标记为对其他社区用户有用。

标签: javascript dom-events


【解决方案1】:

您必须保存对作为参数传递给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 将其删除。

【讨论】:

    【解决方案2】:

    在事件侦听器中,您可以使用if 语句来检查变量是真还是假。然后你把你的事件监听器代码放进去!

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 1970-01-01
      • 2023-03-29
      • 2016-05-06
      • 2021-06-24
      • 2019-12-29
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多