Event listener added on click but runs straight away?

问题: I add an event on click of my button: this.$refs.btn.addEventListener('click', this.turnOn); In the turnOn method I add a listener on the document, to run the turnOff...

问题:

I add an event on click of my button:

this.$refs.btn.addEventListener('click', this.turnOn);

In the turnOn method I add a listener on the document, to run the turnOff method.

turnOn() {
    document.addEventListener('click', this.turnOff);
}

Then during testing, I click the button and the turnOn method runs, but that initial click also runs the document click listener.

How can I run the turnOn method, add the document listener, but not run the document click listener on the initial button click?


回答1:

This is due to event bubbling. You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.

Non-Working

document.querySelector('button').addEventListener('click',(e)=>{
  document.addEventListener('click',()=>console.log("body clicked"));
  console.log("button clicked")
})
<body>
<button>Test</button>
</body>

Note: The above non-working example also adds multiple click events on each click on Test

Working

document.querySelector('button').addEventListener('click',(e)=>{
  e.stopPropagation();
  document.addEventListener('click',()=>console.log("body clicked"));
  console.log("button clicked")
})
<body>
<button>Test</button>
</body>

  • 发表于 2019-03-26 16:06
  • 阅读 ( 216 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除