简体   繁体   English

为什么这段代码中的js事件没有冒泡?

[英]Why does the js event in this code not bubble up?

I want to be able to click on div "three" and it should bubble up to the other two? 我希望能够单击div“三”,它应该冒泡到另外两个?

 const divs = document.querySelectorAll('div'); divs.forEach(div => div.addEventListener('click', function (e) { console.log(e.target.className); })); 
 <div class="one"> <div class="two"> <div class="three"> Hello World </div> </div> </div> 

It does bubble up, you should get 3 log messages. 它确实冒泡了,您应该获得3条日志消息。

It logs three each time because e.target is the original element that the event is bubbling from. 每次记录three因为e.target是事件从中冒泡的原始元素。 To get the current element in the propagation, use e.currentTarget . 要获取传播中的当前元素,请使用e.currentTarget This code logs three, two, one . 此代码记录three, two, one

See What is the exact difference between currentTarget property and target property in javascript 请参阅javascript中currentTarget属性和target属性之间的确切区别是什么

 const divs = document.querySelectorAll('div'); divs.forEach(div => div.addEventListener('click', function (e) { console.log(e.currentTarget.className); })); 
 <div class="one"> <div class="two"> <div class="three"> Hello World </div> </div> </div> 

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

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