将多个事件附加到IE中的按钮问题 [英] attaching multiple events to a button issue in IE
问题描述
< button onclick =fun()> ;绑定< / button>< button id =ttname =tt> Test< / button>
我已经将自定义的bindevent函数写成 attachevent
不支持非IE浏览器。
单击绑定按钮将三个事件绑定到测试按钮。现在点击 Test
按钮,输出结果为:
$ b IE:
3
2
1
Firefox
<1>
2
3
那么有什么办法可以保证在两个浏览器中的执行顺序都是一样的
这是IE8事件模型的一个怪癖。 MSDN对 attachEvent 发表评论:
如果您将多个函数附加到同一个对象上的同一个事件,那么这个函数会在对象的事件之后立即被调用处理程序被调用。
我认为你可以通过注册一个事件处理程序而不是三个来克服它。
函数fun(){
var ele = document.getElementById(tt);
bindEvent(ele,click,function(){
one();
two();
three();
});
}
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
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();
});
}
这篇关于将多个事件附加到IE中的按钮问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!