【问题标题】:Remove event listener on click JS删除单击 JS 上的事件侦听器
【发布时间】:2018-09-05 15:30:48
【问题描述】:

场景:

  • 我将此代码用于页面并将其应用于点击事件,
    现在我无法将其从页面中删除(同样的方式,点击时)。
  • 我该怎么做?

document.addEventListener('touchmove', function(e) {
  e.preventDefault();
}, {
  passive: false
});

【问题讨论】:

  • 您需要创建一个函数,然后您可以为这两个回调设置相同的回调。然后它应该工作。 document.removeEventListener("touchmove", yourfunction);

标签: javascript addeventlistener dom-events


【解决方案1】:

在将事件侦听器绑定/解除绑定到addEventListener 和removeEventListener 方法时,使用命名回调函数touchMove。

要删除的事件侦听器使用以下组合标识 事件类型、事件侦听器函数本身以及各种 可能影响匹配过程的可选选项;

var touchMove = function(e){
  e.preventDefault();
};

document.addEventListener('touchmove', touchMove, { passive: false });

document.removeEventListener('touchmove', touchMove);

【讨论】:

  • 如果添加 var,它是否在页面加载时成为自我可执行的?它会影响passive: false 还是我应该在这个例子中把它放在哪里? @dysfunc
  • 它只是一个函数表达式,不会在页面加载时执行。它将绑定到事件,但在通过事件调用之前不会执行。如果你想调用e.preventDefault(),你实际上不需要传递监听器选项。设置passive: true 将忽略e.preventDefault() 调用。
  • 我需要这个 passive: false 代码,所以我应该把它放在哪里?,用它的其余部分尝试这个(添加和删除添加到点击事件的行)但这对我不起作用,这是我尝试的代码:var touchMove = function(e){ e.preventDefault(); }, { passive: false };@dysfunc
【解决方案2】:

因此,初始化您的按钮以将单击事件侦听器添加到 touchmove 区域,然后从按钮中删除单击功能并进行设置,以便下一个 cick 添加删除事件侦听器以删除单击和触摸事件。基本上是在按钮和 div 上切换事件监听器。

//Touchmove action
function preDef(e) {
  e.preventDefault();
}

//Add the touchmove action and toggle the button to remove the action
function addE(e) {
  e.target.removeEventListener('click', addE, {passive: false});
  e.target.addEventListener('click', removeE, {passive: false});
  document.addEventListener('touchmove', preDef, {passive: false});
}

//Remove the touchmove action and toggle the button to add the action
function removeE(e) {
  e.target.removeEventListener('click', removeE, {passive: false});
  e.target.addEventListener('click', addE, {passive: false});
  document.removeEventListener('touchmove', preDef, {passive: false});
}

//Initialize the add action
document.getElementById('somebutton').addEventListener('click', addE, {passive: false});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 2013-11-08
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多