gpt4 book ai didi

javascript - 为什么事件会在 dom 中冒泡?

转载 作者:行者123 更新时间:2023-11-28 18:21:02 26 4
gpt4 key购买 nike

我了解事件冒泡以及它如何从最内部的元素遍历 dom。我很好奇为什么这是默认行为?

<div>1
<div>2
<div>3
<div>4
<div>5</div>
</div>
</div>
</div>
</div>

如果我在每个部分都有一个事件监听器,但单击 <div>5</div>为什么事件会冒泡到 div4、div3、div2(等)的事件监听器?

编辑:我不认为这是“什么是事件冒泡”的重复,因为这是问为什么而不是什么

最佳答案

如果您问为什么这是默认行为,那么答案是因为 the language specification says so (强调我的):

An event listener consists of these fields:

  • [...]
  • capture (a boolean, initially false)
  • [...]

When an event is dispatched to an object that participates in a tree (e.g. an element), it can reach event listeners on that object’s ancestors too. First all object’s ancestor event listeners whose capture variable is set to true are invoked, in tree order. Second, object’s own event listeners are invoked. And finally, and only if event’s bubbles attribute value is true, object’s ancestor event listeners are invoked again, but now in reverse tree order.

如果您想知道为什么以这种方式定义规范,您可以问自己:
如果您点击了 div5,是否也点击了 div4?
这最终是一个意见问题,但对我来说,答案是肯定的,根据我最初的评论:

If you've been to Geneva, you've been to Switzerland as well.

关于javascript - 为什么事件会在 dom 中冒泡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882274/

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