问题描述
使用Prototype处理点击事件时,我遇到了一个奇怪的问题。如果单击下面代码中的按钮,它将触发三个警报:单击1,单击2和单击3。现代浏览器将按照它们注册的顺序调用侦听器,而IE8(也可能是旧的IE版本)将以相反的顺序调用它们。我发现这很奇怪,因为我认为Prototype维护并执行了一个侦听器队列,这应该是浏览器独立的。这不是这样吗?如果没有,事件监听器是按照某个顺序运行还是异步,因此它们的顺序无关紧要?
I've come across an oddity while using Prototype to handle click events. If you click the button in the code below, it will trigger three alerts: 'Click 1', 'Click 2' and 'Click 3'. Modern browsers will invoke the listeners in the order they are registered in, while IE8 (and perhaps older IE versions as well) will invoke them in the opposite order. I find this odd because I thought Prototype maintained and executed a queue of listeners, which should be browser independent. Is this not so? If not, are event listeners supposed to be run in a certain order or are they asynchronous and thus their order irrelevant?
<button id="button">Click me</button>
<script type="text/javascript">
$('button').observe('click', function(event) {
alert('Click 1');
});
$('button').observe('click', function(event) {
alert('Click 2');
});
$('button').observe('click', function(event) {
alert('Click 3');
});
</script>
推荐答案
Prototype依赖于浏览器的底层触发机制(并非所有图书馆都这样做,见下文)。事件处理程序被触发的顺序最初不是由DOM事件保证的。来自 :
Prototype relies on the browser's underlying firing mechanism for order (not all libraries do, see below). The order in which event handlers are fired was not guaranteed by the DOM events stuff originally. From the DOM2 Events specification:
绝大多数浏览器实现(Chrome,Firefox,Opera等),包括IE9,都按照它们附加的顺序触发处理程序。 IE8和更早版本则相反。
The vast majority of browser implementations (Chrome, Firefox, Opera, etc.), including IE9, fire the handlers in the order in which they were attached. IE8 and earlier do it the other way around.
较新的仍在进行中,它引入了按注册顺序触发它们的要求(大多数浏览器都这样做):
The newer DOM3 event spec, still a work in progress, introduces the requirement that they be fired in order of registration (what most browsers do):
...其中可能是IE9为什么会这样做的一部分(IE9明显改善了微软对事件标准的支持,增加了 addEventListener
等)。
...which is probably part of why IE9 does that now (IE9 markedly improved Microsoft's support for the events standards, adding addEventListener
, etc.).
一些JavaScript库(例如jQuery)做保证订单,无论浏览器如何,每个元素每个事件只附加一个处理程序,并维护自己的用户代码处理程序列表。
Some JavaScript libraries (jQuery for instance) do guarantee the order regardless of the browser, by attaching only a single handler per event per element and maintaining their own list of user code handlers to fire.
这篇关于多事件监听器的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!