attachEvent versus addEventListener

一世执手 提交于 2019-12-17 18:07:24

问题


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.

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

Here's the code:

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);
    }
}

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 */
}

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.

Any help is highly appreciated!


回答1:


Here's how to make this work cross-browser, just for reference though.

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




回答2:


The source of your problems is the KeyBoardHandler function. Specifically, in IE Event objects do not have a target property: the equivalent is srcElement. Also, the returnValue property of Event objects is IE-only. You want the preventDefault() method in other browsers.

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 */
}



回答3:


Just use a framework like jQuery or prototype. That's what they are there for, this exact reason: being able to do this sort of thing w/out having to worry about cross-browser compatibility. It's super easy to install...just include a .js script and add a line of code...

(edited just for you Crescent Fresh)

With a framework, the code is as simple as...

<script type='text/javascript' src='jquery.js'></script>
$('element').keyup(function() { 
  // stuff to happen on event here
});



回答4:


Here is a function I use for both browsers:

function eventListen(t, fn, o) {
    o = o || window;
    var e = t+Math.round(Math.random()*99999999);
    if ( o.attachEvent ) {
        o['e'+e] = fn;
        o[e] = function(){
            o['e'+e]( window.event );
        };
        o.attachEvent( 'on'+t, o[e] );
    }else{
        o.addEventListener( t, fn, false );
    }
}

And you can use it like:

eventListen('keyup', function(ev){
  if (ev.keyCode === 13){
    ...
  }
  ...
}, Editor)



回答5:


Different browsers will process events differently. Some browsers have event bubble up throw the controls where as some go top down. For more information on that take a look at this W3C doc: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow

As for this specific issue setting the "userCapture" parameter to false for the addEventListener will make events behave the same as Internet Explorer: https://developer.mozilla.org/en/DOM/element.addEventListener#Internet_Explorer




回答6:


You might be better off using a JavaScript framework such as MooTools or jQuery of your choice to ease cross-browser support. For details, see also

  • http://mootools.net/docs/core/Element/Element.Event
  • http://api.jquery.com/category/events/

MooTools port of parts of your sample code:

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);

By the way, is it on purpose that you use both idname and this.idname in the code above ?



来源:https://stackoverflow.com/questions/3743446/attachevent-versus-addeventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!