JavaScript addEventListener 为什么这里不冒泡?
JavaScript addEventListener why does it not bubble here?
AFAIK 使用点击事件和 addEventListener()
应该从最里面的元素冒泡到最外面的父元素。那么下面的代码有什么问题呢?
function ChangeBackground(e){
e.target.style.background = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
}
var all= document.querySelectorAll("div,span,p");
for(var i=0; i<all.length;i++){
all[i].addEventListener("click",ChangeBackground);
}
div, span, p{
display: inline-block;
padding: 10px;
border: 1px solid;
}
<span>span
<div>div
<p>p</p>
</div>
<p>p</p>
</span>
<div>div
<div>div
<div>div</div>
</div>
<div>div</div>
</div>
当我单击 p
时,它不会更改其父元素的背景。
确实有泡沫。问题出在我引用 e.target
而不是 this
的处理程序中。这是更正后的代码片段:
(注意默认背景是透明的。)
function ChangeBackground(e){
this.style.background = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
}
var all= document.querySelectorAll("div,span,p");
for(var i=0; i<all.length;i++){
all[i].addEventListener("click",ChangeBackground,false);
}
div, span, p{
display: inline-block;
padding: 10px;
border: 1px solid;
}
<span>span
<div>div
<p>p</p>
</div>
<p>p</p>
</span>
<div>div
<div>div
<div>div</div>
</div>
<div>div</div>
</div>
AFAIK 使用点击事件和 addEventListener()
应该从最里面的元素冒泡到最外面的父元素。那么下面的代码有什么问题呢?
function ChangeBackground(e){
e.target.style.background = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
}
var all= document.querySelectorAll("div,span,p");
for(var i=0; i<all.length;i++){
all[i].addEventListener("click",ChangeBackground);
}
div, span, p{
display: inline-block;
padding: 10px;
border: 1px solid;
}
<span>span
<div>div
<p>p</p>
</div>
<p>p</p>
</span>
<div>div
<div>div
<div>div</div>
</div>
<div>div</div>
</div>
当我单击 p
时,它不会更改其父元素的背景。
确实有泡沫。问题出在我引用 e.target
而不是 this
的处理程序中。这是更正后的代码片段:
(注意默认背景是透明的。)
function ChangeBackground(e){
this.style.background = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
}
var all= document.querySelectorAll("div,span,p");
for(var i=0; i<all.length;i++){
all[i].addEventListener("click",ChangeBackground,false);
}
div, span, p{
display: inline-block;
padding: 10px;
border: 1px solid;
}
<span>span
<div>div
<p>p</p>
</div>
<p>p</p>
</span>
<div>div
<div>div
<div>div</div>
</div>
<div>div</div>
</div>