Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
308 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...