Javascript 中的事件传播 [英] Event propagation in Javascript

查看:22
本文介绍了Javascript 中的事件传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个元素 (html) 嵌套在另一个元素中,并且它们都附加了一个单击处理程序,则单击内部元素会执行其单击处理程序,然后向上冒泡到父元素并执行其单击处理程序.我是这么理解的.

If I have an element (html) nested in another element and both of them have a click handler attached, clicking the inner element executes its click handler and then bubbles up to the parent and executes its click handler. That's how I understand it.

如果没有附加相同的事件,事件是否会在 DOM 树中冒泡?如果是,是否值得在每个处理程序的末尾放置一个 event.stopPropagation() 来阻止这种情况并加快速度?

Do events bubble up the DOM tree if there are no events attached that are the same and if so, is it worth putting a event.stopPropagation() at the end of every handler to stop this and speed things up?

推荐答案

除非设置 event.cancelBubble=true 或使用 event.stopPropagation(),否则事件几乎总是冒泡.但是,只有当您的事件之一时,您才会意识到这一点处理程序被绊倒.

events almost always bubble up unless event.cancelBubble=true is set or event.stopPropagation() is used. You are only aware of it, though, when one of your event handlers gets tripped.

请参阅 http://en.wikipedia.org/wiki/DOM_events 以获取列表冒泡的事件.(注:在HTML事件表中,cancelable指的是event.preventDefault()的有效性,或者return false取消默认动作,不冒泡)

See http://en.wikipedia.org/wiki/DOM_events for a list of events which bubble. (Note: in the table of HTML events, cancelable refers to the effectiveness of event.preventDefault() or return false to cancel the default action, not bubbling)

另见http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow,特别是 1.2.1 基本流程,以了解事件传播的捕获阶段和冒泡阶段.

Also see http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow, in particular 1.2.1 Basic Flow to understand the capture phase and bubbling phase of event propagation.

编辑

http://mark-story.com/posts/view/speed-up-javascript-event-handling-with-event-delegation-and-bubbling 表明通过停止性能提升传播但不提供数据.

http://mark-story.com/posts/view/speed-up-javascript-event-handling-with-event-delegation-and-bubbling suggests there is a performance gain by stopping propagation but provides no data.

http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/a9af0aa4216a8046 建议浏览器应该针对冒泡行为进行优化,并表示应该没有显着的性能差异.再次没有数据.

http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/a9af0aa4216a8046 suggests that browsers should be optimized for bubbling behaviour and says there should be no significant performance difference. Again no data.

http://developer.yahoo.com/performance/rules.html#events 提供了一种提高事件处理性能的好技术,但没有直接谈论 stopPropagation 性能.

http://developer.yahoo.com/performance/rules.html#events provides a good technique for improving event-handling performance, but doesn't directly talk about stopPropagation performance.

最终,您必须分析差异才能很好地了解您网站上的优势.

Ultimately, you'd have to profile the difference to get a good idea of the benefits on your site.

这篇关于Javascript 中的事件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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