单击按钮添加事件:
this.$refs.btn.addEventListener('click', this.turnOn);
Run Code Online (Sandbox Code Playgroud)
在turnOn方法中,我在文档上添加了一个侦听器以运行该turnOff方法。
turnOn() {
document.addEventListener('click', this.turnOff);
}
Run Code Online (Sandbox Code Playgroud)
然后在测试过程中,我单击了按钮,该turnOn方法开始运行,但是该初始单击也运行了文档单击侦听器。
如何运行该turnOn方法,添加文档侦听器,但不单击初始按钮单击就运行文档单击侦听器?
Mah*_*Ali 10
这是由于事件冒泡引起的。当您单击<button>连接到主体的eventListener时,由于该事件起泡而被调用。
您可以防止使用event.stopPropgation()。以下是两个片段,以了解它们之间的区别。
document.querySelector('button').addEventListener('click',(e)=>{
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
})Run Code Online (Sandbox Code Playgroud)
<body>
<button>Test</button>
</body>Run Code Online (Sandbox Code Playgroud)
注意:上面的无效示例还在Test的每次点击上添加了多个click事件
document.querySelector('button').addEventListener('click',(e)=>{
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
})Run Code Online (Sandbox Code Playgroud)
<body>
<button>Test</button>
</body>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |