attachEvent和addEventListener [英] attachEvent versus addEventListener

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

问题描述

我有麻烦让attachEvent工作。在所有支持addEventListener处理程序的浏览器中,下面的代码像一个charm,但在IE是一个完整的灾难。它们有自己的(不完全)变量,称为attachEvent。

I'm having troubles getting the attachEvent to work. In all browsers that support the addEventListener handler the code below works like a charm, but in IE is a complete disaster. They have their own (incomplete) variation of it called attachEvent.

现在这是交易。如何获得attachEvent以同样的方式addEventListener工作?

Now here's the deal. How do I get the attachEvent to work in the same way addEventListener does?

这里是代码:

function aFunction(idname)
{
    document.writeln('<iframe id="'+idname+'"></iframe>');
    var Editor = document.getElementById(idname).contentWindow.document;

    /* Some other code */

    if (Editor.attachEvent)
    {
        document.writeln('<textarea id="'+this.idname+'" name="' + this.idname + '" style="display:none">'+this.html+'</textarea>');
        Editor.attachEvent("onkeyup", KeyBoardHandler);
    }
    else
    {
        document.writeln('<textarea id="hdn'+this.idname+'" name="' + this.idname + '" style="display:block">'+this.html+'</textarea>');
        Editor.addEventListener("keyup", KeyBoardHandler, true);
    }
}

这会调用函数KeyBoardHandler, / p>

This calls the function KeyBoardHandler that looks like this:

function KeyBoardHandler(Event, keyEventArgs) {
    if (Event.keyCode == 13) {
        Event.target.ownerDocument.execCommand("inserthtml",false,'<br />');
        Event.returnValue = false;
    }

    /* more code */
}

我不想使用任何框架,因为A)我想学习和理解的东西,B)任何框架只是一个重载的代码,我要使用。

I don't want to use any frameworks because A) I'm trying to learn and understand something, and B) any framework is just an overload of code I'm nog going to use.

任何帮助都非常感谢!

推荐答案

var myFunction=function(){
  //do something here
}
var el=document.getElementById('myId');

if (el.addEventListener) {
  el.addEventListener('mouseover',myFunction,false);
  el.addEventListener('mouseout',myFunction,false);
} else if(el.attachEvent) {
  el.attachEvent('onmouseover',myFunction);
  el.attachEvent('onmouseout',myFunction);
} else {
  el.onmouseover = myFunction;
  el.onmouseout = myFunction;
}

ref:http://jquerydojo.blogspot.com/2012/12/javascript-dom-addeventlistener-and.html

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

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