Javascript 中的 MSIE 和 addEventListener 问题? [英] MSIE and addEventListener Problem in Javascript?

查看:32
本文介绍了Javascript 中的 MSIE 和 addEventListener 问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

document.getElementById('container').addEventListener('copy',beforecopy,false );

在Chrome/Safari中,当页面上的内容被复制时,上面将运行beforecopy"功能.MSIE 也应该支持此功能,但由于某种原因,我收到此错误:

In Chrome / Safari, the above will run the "beforecopy" function when the content on the page is being copied. MSIE is supposed to support this functionality as well, but for some reason I'm getting this error:

对象不支持此属性或方法"

"Object doesn't support this property or method"

现在,我的理解是 Internet Explorer 不会使用 body 节点,但我认为通过 ID 提供节点会正常工作.有没有人对我做错了什么有任何想法?提前致谢.

Now, it's my understanding that Internet Explorer won't play with the body node, but I would have thought providing a node by ID would work fine. Does anyone have any ideas about what I'm doing wrong? Thanks in advance.

** 任何能告诉我第三个参数False"有什么用处的人都会加分.

** Bonus points for anyone who can tell me what the 3rd parameter "False" is good for.

推荐答案

在 IE 中你必须使用 attachEvent 而不是标准的 addEventListener.

In IE you have to use attachEvent rather than the standard addEventListener.

一个常见的做法是检查addEventListener方法是否可用并使用它,否则使用attachEvent:

A common practice is to check if the addEventListener method is available and use it, otherwise use attachEvent:

if (el.addEventListener){
  el.addEventListener('click', modifyText, false); 
} else if (el.attachEvent){
  el.attachEvent('onclick', modifyText);
}

你可以创建一个函数来做到这一点:

You can make a function to do it:

function bindEvent(el, eventName, eventHandler) {
  if (el.addEventListener){
    el.addEventListener(eventName, eventHandler, false); 
  } else if (el.attachEvent){
    el.attachEvent('on'+eventName, eventHandler);
  }
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
  alert('element clicked');
});

您可以在此处运行上述代码的示例.

You can run an example of the above code here.

addEventListener 的第三个参数是 useCapture;如果为 true,则表示用户希望启动事件捕获.

The third argument of addEventListener is useCapture; if true, it indicates that the user wishes to initiate event capturing.

这篇关于Javascript 中的 MSIE 和 addEventListener 问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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