addEventListener in Internet Explorer

后端 未结 8 2043
感情败类
感情败类 2020-11-22 14:33

What is the equivalent to the Element Object in Internet Explorer 9?

if (!Element.prototype.addEventListener) {
    Element.prototype.addEventListener = func         


        
相关标签:
8条回答
  • 2020-11-22 15:00

    John Resig, author of jQuery, submitted his version of cross-browser implementation of addEvent and removeEvent to circumvent compatibility issues with IE's improper or non-existent addEventListener.

    function addEvent( obj, type, fn ) {
      if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
    }
    function removeEvent( obj, type, fn ) {
      if ( obj.detachEvent ) {
        obj.detachEvent( 'on'+type, obj[type+fn] );
        obj[type+fn] = null;
      } else
        obj.removeEventListener( type, fn, false );
    }
    

    Source: http://ejohn.org/projects/flexible-javascript-events/

    0 讨论(0)
  • 2020-11-22 15:02

    As Delan said, you want to use a combination of addEventListener for newer versions, and attachEvent for older ones.

    You'll find more information about event listeners on MDN. (Note there are some caveats with the value of 'this' in your listener).

    You can also use a framework like jQuery to abstract the event handling altogether.

    $("#someelementid").bind("click", function (event) {
       // etc... $(this) is whetver caused the event
    });
    
    0 讨论(0)
提交回复
热议问题