attachEvent与addEventListener

Léo*_*éon 12 javascript cross-browser

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

现在这是交易.如何以与addEventListener相同的方式使attachEvent工作?

这是代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这会调用KeyBoardHandler函数,如下所示:

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

    /* more code */
}
Run Code Online (Sandbox Code Playgroud)

我不想使用任何框架,因为A)我正在尝试学习和理解某些东西,并且B)任何框架只是我将要使用的代码的重载.

任何帮助都非常感谢!

小智 14

以下是如何使这项工作跨浏览器,仅供参考.

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;
}
Run Code Online (Sandbox Code Playgroud)

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


Tim*_*own 7

问题的根源是KeyBoardHandler功能.具体来说,在IE Event对象中没有target属性:等价物srcElement.此外,对象的returnValue属性Event仅限IE.您希望preventDefault()在其他浏览器中使用该方法.

function KeyBoardHandler(evt, keyEventArgs) {
    if (evt.keyCode == 13) {
        var target = evt.target || evt.srcElement;
        target.ownerDocument.execCommand("inserthtml",false,'<br />');
        if (typeof evt.preventDefault != "undefined") {
            evt.preventDefault();
        } else {
            evt.returnValue = false;
        }
    }

    /* more code */
}
Run Code Online (Sandbox Code Playgroud)


Arc*_*dix 0

您可能最好使用您选择的 JavaScript 框架(例如MooToolsjQuery)来简化跨浏览器支持。有关详细信息,另请参阅

部分示例代码的 MooTools 端口:

var Editor = $(idname).contentWindow.document;
...
$(document.body).grab(new Element('textarea', {
    'id'   : this.idname,
    'name' : this.idname,
    'style': 'display:none;',
    'html' : this.html
});
Editor.addEvent('keyup', KeyBoardHandler);
Run Code Online (Sandbox Code Playgroud)

顺便问一下,您在上面的代码中同时使用idname和是故意的吗?this.idname

  • 谢谢大家,但不用谢。;-) 首先,我想在这里学习一些东西,其次,我不想要过多的我不会使用的代码。因此,请不要提供外部框架建议,尽管我理解其背后的想法。 (3认同)