问题
I am working on very old application designed in early 2000. The page work on IE9 perfectly but not on firefox. After a lot of digging I got one issue. I have reproduced that in this simple example.
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
function fun() {
var ele = document.getElementById("tt");
bindEvent(ele, "click", one);
bindEvent(ele, "click", two);
bindEvent(ele, "click", three);
}
function one() {
alert("1");
}
function two() {
alert("2");
}
function three() {
alert("3");
}
<button onclick="fun()">Bind</button>
<button id="tt" name="tt">Test</button>
I have written the custom bindevent function as attachevent
not supported by non IE browser.
Clicking upon Bind button will bind three events to Test button. Now Clicking upon Test
button the output is
IE:
3 2 1
Firefox
1 2 3
So is there any way I can ensure in both browser the execution order will be same
回答1:
This is a quirk of IE8 event model. MSDN makes a remark on attachEvent:
If you attach multiple functions to the same event on the same object, the functions are called in random order, immediately after the object's event handler is called.
I think you can overcome it by registering only one event handler instead of three.
function fun() {
var ele = document.getElementById("tt");
bindEvent(ele, "click", function() {
one();
two();
three();
});
}
来源:https://stackoverflow.com/questions/27420580/attaching-multiple-events-to-a-button-issue-in-ie