为什么事件会冒泡 dom?

Why do events bubble up the dom?

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

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

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

编辑:我不认为这是 "what is event bubbling" 的重复,因为这是在问 为什么 而不是什么

如果你问为什么这是默认行为,那么答案是因为 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.

你的说法是错误的。 The default for simple events is not to bubble:

Firing a simple event named e means that a trusted event with the name e, which does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and which uses the Event interface, must be created and dispatched at the given target.

所以 HTML 相关事件冒泡是因为规范明确如此说明,大概是因为这样更有意义。

一些冒泡的事件:

一些不冒泡的事件: