下面是一些演示代码:
<div id="test">
<div class="child">
click
</div>
</div>
<script>
document.addEventListener('click', function (e) {
if(e.target.classList.contains('child')){
console.log('child')
}
if(e.target.id==='test'){
console.log('test')
}
if(e.target.tagName === 'HTML'){
console.log('html')
}
}, false)
</script>
当我单击文本时,控制台仅记录“child”。为什么点击事件没有冒泡到父节点#test?连html元素都获取不到点击事件。
谁能解释一下是什么问题?
最佳答案
事件正在冒泡,这就是注册到文档对象的句柄被触发的原因。文档对象是 dom 中最顶层的对象,即它是 html 元素的父级。如果没有发生冒泡,那么处理程序就不会被调用。
但是在所有处理程序中Event.target将引用事件开始的原始元素,这就是为什么它总是引用子元素
A reference to the object that dispatched the event. It is different than event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.
如果要测试祖先元素,则需要从事件目标向上遍历,看是否有满足条件的
document.addEventListener('click', function(e) {
var target = e.target;
while (target) {
if (target.classList.contains('child')) {
snippet.log('child')
}
if (target.id === 'test') {
snippet.log('test')
}
if (target.tagName === 'HTML') {
snippet.log('html')
}
target = target.parentNode;
}
}, false)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div id="test">
<div class="child">
click
</div>
</div>
关于javascript - 为什么我的事件没有冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32201239/