gpt4 book ai didi

javascript - 最内层元素上的调度事件不会导致向上层元素冒泡?

转载 作者:行者123 更新时间:2023-12-02 23:17:04 25 4
gpt4 key购买 nike

innerDiv = document.getElementById("inner");
innerDiv.onclick = function(e) {
console.log("PURPLE COLOR DIV");

}

outterDiv = document.getElementsByClassName("outter")[0];
outterDiv.onclick = function(e) {
console.log("ORANGE COLOR DIV");
};

containerDiv = document.getElementsByClassName("container")[0];
containerDiv.onclick = function() {
console.log("RED COLOR DIV");
}

setTimeout(() => document.getElementById("inner").dispatchEvent(new Event('click'), {
bubbles: true
}), 2000)
.container {
width: 260px;
height: 170px;
background-color: maroon;
padding-top: 40px;
}

.outter {
width: 200px;
height: 80px;
background: orange;
margin: 0 auto;
padding-top: 35px;
}

#inner {
background: purple;
width: 100px;
height: 50px;
margin: auto;
}
<div class="container">
<div class="outter">
<div id="inner"></div>
</div>
</div>

问题

setTimeout 导致dispatchEvent 触发后,橙色和红色回调不会执行。如果 bubbles 属性设置为 true,为什么会出现这种情况?如果单击 UI 紫色 div,冒泡会按预期完成其工作。

fiddle 示例:http://jsfiddle.net/0tko5qwe/

最佳答案

您需要将选项添加到 Event() 构造函数本身:

new Event('click', { bubbles: true})

innerDiv = document.getElementById("inner");
innerDiv.onclick = function(e) {
console.log("PURPLE COLOR DIV");

}

outterDiv = document.getElementsByClassName("outter")[0];
outterDiv.onclick = function(e) {
console.log("ORANGE COLOR DIV");
};

containerDiv = document.getElementsByClassName("container")[0];
containerDiv.onclick = function() {
console.log("RED COLOR DIV");
}

setTimeout(() => document.getElementById("inner").dispatchEvent(new Event('click', {
bubbles: true
})), 500)
.container {
width: 260px;
height: 170px;
background-color: maroon;
padding-top: 40px;
}

.outter {
width: 200px;
height: 80px;
background: orange;
margin: 0 auto;
padding-top: 35px;
}

#inner {
background: purple;
width: 100px;
height: 50px;
margin: auto;
}
<div class="container">
<div class="outter">
<div id="inner"></div>
</div>
</div>

关于javascript - 最内层元素上的调度事件不会导致向上层元素冒泡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com