单击JS删除事件侦听器

问题描述 投票:0回答:2

场景:

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

document.addEventListener('touchmove', function(e) {
  e.preventDefault();
}, {
  passive: false
});
javascript addeventlistener dom-events
2个回答
1
投票

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

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

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

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

document.removeEventListener('touchmove', touchMove);

0
投票

因此,初始化按钮以在点击触摸移动区域时添加事件侦听器,然后从按钮中删除单击功能并进行设置,以便下一个cick添加remove事件侦听器以移除click和touch事件。基本上切换按钮和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});
© www.soinside.com 2019 - 2024. All rights reserved.