问题:
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>