简体   繁体   English

addEventListener 和传递 function 的问题

[英]Problem with addEventListener and passing function

My problem is that when I clicked one of this boxes function mark is call of 9 times.我的问题是,当我单击其中一个框时,function 标记被调用了 9 次。 Why is this happening?为什么会这样? I also add that boxes have 9 elements.我还补充说盒子有 9 个元素。

export function battle(app, mod, player) {

  const newHtml = html.replace("mode", mod.toUpperCase());

  app.innerHTML = newHtml;

  const boxes = document.querySelectorAll('.battle div');

  if (mod = 'single') {
    boxes.forEach(elem => addEventListener('click', (e) => {
      mark(e.target, player);
    }, false));
  }
  if (mod = 'multi') {

  }
}

You are calling addEventListener which is akin to window.addEventListener , so you are attaching 9 event handlers to the window object.您正在调用类似于window.addEventListeneraddEventListener ,因此您将 9 个事件处理程序附加到window object。 A click anywhere will trigger all of them.在任何地方单击都会触发所有这些。

You need to add the event listener to the boxes.您需要将事件侦听器添加到框中。

elem => elem.addEventListener

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM