首页 > 解决方案 > 有什么办法可以暂停所有的事件监听器?

问题描述

有没有办法暂停所有“点击”事件监听器,以便我添加的新点击事件监听器单独工作?我需要稍后恢复所有预先存在的事件侦听器。

谢谢你

编辑:我添加了使用 stopPropogation() 方法添加新单击事件侦听器的结尾。为了恢复所有预先存在的事件监听器,我刚刚删除了新的点击监听器。它工作得很好!

感谢您的支持 !

标签: javascripteventsclickdom-eventsonclicklistener

解决方案


您可以通过一个中心函数路由所有听众,该函数是否应该继续。

let elems = document.querySelectorAll(".thing");

elems.forEach(el => el.addEventListener('click', function(e) {
  if (okForMeToRun(e)) {
    console.log('I am allowed')
  } else {
    console.log('I am not allowed');
  }
}));

function okForMeToRun(e) {
  // in case we need to examine the event that wants to fire...
  console.log(e.target.innerText + ' wants to fire ')
  if (e.target.classList.contains('goodtogo')) return true;

  return false;
}
<button class='thing goodtogo'>Test me </button> <button class='thing'>Then test me </button>


推荐阅读