Internet Explorer and JavaScript event currentTarget

后端 未结 13 2251
执笔经年
执笔经年 2020-11-30 05:36

Is there a way to take the current target of an event with IE 7 or 8?

With other browser (firefox, opera, chrome etc.) we can use event.currentTarget or

13条回答
  •  天涯浪人
    2020-11-30 05:56

    This function creates currentTarget in case it is IE, so you no longer need to patch your code!

    function eventListener(e,t,f) {
       if(e.addEventListener)
           e.addEventListener(t,f);
       else
           e.attachEvent('on' + t,
                         function(a){
                             a.currentTarget = e;
                             f(a);
                         });
    }
    

    Regular JS(will not work on IE below 9):

    function myfunction(e) {
        alert(e.currentTarget.id);
    }
    
    e = document.getElementById('id');
    e.AddEventListener(e,'mouseover',myfunction);
    

    With this function(will work on IE below 9):

    function myfunction(e) {
        alert(e.currentTarget.id);
    }
    e = document.getElementById('id');
    eventListener(e,'mouseover',myfunction);
    

提交回复
热议问题