将多个事件附加到IE中的按钮问题 [英] attaching multiple events to a button issue in IE

查看:125
本文介绍了将多个事件附加到IE中的按钮问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事于2000年初设计的非常旧的应用程序。该页面在IE9上完美工作,但不在Firefox上。经过大量的挖掘,我得到了一个问题。我已经在这个简单的例子中重现了这一点。



(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); ()函数一(){alert(1);} }

< 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屋!

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