事件冒泡/捕获 - 它从哪里开始/结束? [英] Event bubbling/capturing - where does it start/end?

查看:244
本文介绍了事件冒泡/捕获 - 它从哪里开始/结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,事件有两种模式 - 冒泡和捕捉。

I understand that an event has two modes -- bubbling and capturing.

当一个事件设置为bubble时,Javascript会检查到document吗?

When an event is set to bubble, does Javascript checks up to "document" ?

当一个事件发生时设置为捕获,Javascript是否始终从文档开始?

When an event is set to capture, does Javascript always starts from "document"?

Javascript如何知道停止/启动的位置?

How does Javascript know where to stop/start ?

更新:

假设我的身体标签中有以下代码。

Let's say I have the following code in my body tag.

<div id='outer'>
    <div id='inner'></div>
</div>

当我将事件设置为#inner来冒泡时,Javascript会检查文档还是停止在#outer?

When I set an event to #inner to bubble, does Javascript check up to document or does it stop at #outer?

推荐答案

事件冒泡

JavaScript一直检查文档。如果您在文档上添加侦听器并在内部添加侦听器,则两个侦听器都会触发。

JavaScript checks all the way up to document. If you add a listener on document and a listener on inner, both listeners fire.

事件捕获

JavaScript从文档开始,一直到内部。如果您在文档上添加侦听器并在内部添加侦听器,则两个侦听器都会触发。




我的结果

JavaScript starts from document and goes all the way down to inner. If you add a listener on document and a listener on inner, both listeners fire.


My Findings

原来,浏览器进行某种智能处理,以便

Turns out that the browser does some sort of smart processing so that it

a)不必循环整个父级层次

a) doesn't have to loop through the entire parent hierachy

b)不必遍历所有事件。




证明

b) doesn't have to loop through all events.


Proof

a)浏览器没时间触发单击内部div时单击事件:

a) It takes the browser no time to trigger both click events when the inner div is clicked:

Fiddle

b)当存在许多附加到其他DOM元素的其他事件时,单击内部div时浏览器没有时间触发两个单击事件在父级别中:

b) It takes the browser no time to trigger both click events when the inner div is clicked when lots of other events exist that are attached to other DOM elements not in the parent hierachy:

小提琴

这篇关于事件冒泡/捕获 - 它从哪里开始/结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆