How to access Event.target in IE9?

前端 未结 6 643
耶瑟儿~
耶瑟儿~ 2021-02-08 02:12

The HTML DOM object model defines an Event object with a target property.

Looking at MSDN, Microsoft documents a target property. They also document srcElem

6条回答
  •  醉梦人生
    2021-02-08 02:49

    Here goes for my investigation (tested in IE9, IE10 & Edge browser modes on IE11, IE8 unfortunately breaks jsFiddle). In IE9 mode (IE11) event.target was available as a local variable to the function, don't know if it differs from the real IE9.

    You cannot access event in any browser with an inline function. The problem is that when you do

    
    

    and you pass this as parameter, this === event.target (or srcElement), namely a [HTML Object], not an [Event Object].

    So in practice that means that this:

    is the same as:

    // note that onclick perfectly works, you don't necessarily need addEventListener
    document.getElementById('foo').onclick = function(e) { alert(e.target) } //or
    document.getElementById('foo').addEventListener('click', function(e) { alert(e.target) }, false);
    

    So you access event target either directly inline as the parameter, either through javascript as the object parameter's target || srcElement property. You can test the results for yourself here: http://jsfiddle.net/kevinvanlierde/tg6FP/2/

    Note: In case you attach inline, the position of your scripts is crucial (right before closing body tag)
    Note: In case you attach inline, given that event.target is the 'root' of the object passed, you cannot access other event properties, like event.type.
    Note: Be careful with IE Developer mode. I've known it to be deceiving (eg, not correctly displaying DOM content in the element tree until you click 'Edit as HTML')

提交回复
热议问题