JavaScript 事件处理程序的执行顺序
如果多个事件处理程序附加到相同元素上的同一事件,它们按什么顺序执行?
我看过 this 这是更具体的点击事件。 这表示标准没有指定有关顺序的任何内容。
所以,我的问题是,事件按什么顺序执行? (该事件可以是任何事件,可以是同步的或异步的)
If multiple event handlers are attached to same event on the same elements, in which order are they executed?
I have had a look at this which is more specific to click event. this says that standards do not specify anything about order.
So, my question is, in what order events are executed? (that event can be any event may be synchronous or asynchronous)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,通过经验测试,单击事件处理程序按照它们附加到对象的顺序执行。附加的第一个是第一个执行的。
这是我在 Chrome、Firefox、IE9 和 Safari 中运行的测试床,它们都按照最初附加的顺序执行事件处理程序。
工作测试台:http://jsfiddle.net/jfriend00/yTYxV/
As best I can tell through empirical testing, the click event handlers are executed in the order they were attached to the object. The first one attached is the first one to execute.
Here's a test bed that I ran in Chrome, Firefox, IE9 and Safari and they all executed the event handlers in the order they were initially attached.
Working test bed: http://jsfiddle.net/jfriend00/yTYxV/
事件处理程序的执行顺序并不重要。我不能肯定地说,但我认为该标准没有对此做出任何规定。每个实现都可以自由选择最适合其流程的算法。
事件处理程序应该是独立的。事件处理程序不应依赖于另一个事件处理程序或另一个处理程序的执行效果。事件处理程序甚至不应该知道为同一事件安装了其他处理程序。
如果这对您来说很重要,那么处理程序之间就存在耦合。耦合要么是人为的(例如,某些数据结构是共享的,不是因为它需要共享,而是因为这是编写代码时最简单的方法),在这种情况下您可以删除它,或者耦合表明应该留在一个处理程序中的处理已被人为地分成两个(或更多)单独的处理程序。
事实上,您的问题揭示了应用程序架构中的问题。解决问题(使事件处理程序独立),神奇的是,您将不再关心它们的执行顺序。额外的好处是,您的应用程序将得到更好的设计,并且更容易修改和推理其行为。
The order of execution of the event handlers should not matter. I cannot tell for sure but I think that the standard does not specify anything about that. Each implementation is free to choose whatever algorithm fits their flow best.
The event handlers should be independent. An event handler should not depend on another event handler or on the effects of the execution of another handler. An event handler should not even know that other handlers are installed for the same event.
If it does matter for you, then you have a coupling between the handlers. Either the coupling is artificial (for example, some data structure is shared, not because it needs to be shared but because that was the easiest way when the code has been written) and in this case you can remove it, or the coupling shows that the processing that should stay in one handler has been artificially split into two (or more) separate handlers.
Your question, in fact, reveals a problem in the architecture of the application. Solve the problem (make the event handlers independent) and, magically, you won't care any more in which order they are executed. Bonus, your application will be better designed and easier to modify and reason about its behaviour.