Access event.target in IE8 unobtrusive Javascript

前端 未结 4 1336
忘掉有多难
忘掉有多难 2021-01-04 01:37

The following function gets the target element in a dropdown menu:

function getTarget(evt){

 var targetElement = null;

 //if it is a standard browser
 if (         


        
相关标签:
4条回答
  • 2021-01-04 02:18

    Shortest version ever seen:

    function getTarget(e) {
    var evn = e || window.event;
    return evn.srcElement || e.target;
    }
    
    0 讨论(0)
  • 2021-01-04 02:20

    The problem is that in IE, the event object is not sent as an argument of the handler, it is just a global property (window.event):

    function getTarget(evt){
     evt = evt || window.event; // get window.event if argument is falsy (in IE)
    
     // get srcElement if target is falsy (IE)
     var targetElement = evt.target || evt.srcElement;
    
     //return id of <li> element when hovering over <li> or <a>
     if (targetElement.nodeName.toLowerCase() == 'li'){
      return targetElement;
     }
     else if (targetElement.parentNode.nodeName.toLowerCase() == 'li'){
    
        return targetElement.parentNode;
     }
     else{
        return targetElement;
     }
    
    0 讨论(0)
  • 2021-01-04 02:28

    In my experience, the problem you describe is not related to where the event is obtained (window or handler parameter) but rather due to whether or not the event was raised "properly". For example, if you have a text input element and you call its onchange method without passing in an event object, the event.srcElement property will be null.

    The following code from Jehiah is useful

    function fireEvent(element,event){
       if (document.createEventObject){
          // dispatch for IE
          var evt = document.createEventObject();
          return element.fireEvent('on'+event,evt)
       }
       else{
          // dispatch for firefox + others
          var evt = document.createEvent("HTMLEvents");
          evt.initEvent(event, true, true ); // event type,bubbling,cancelable
          return !element.dispatchEvent(evt);
       }
    }
    

    Example call:

    fireEvent(element,'change');
    
    0 讨论(0)
  • 2021-01-04 02:33

    I met this problem too. And the problem is: in IE8, the event must be window.event, not the event that is declared in params.

    I fixed as below:

        function onclick(event){
          if (is_ie8()){
            clicked_element = window.event.srcElement
          } else {
            clicked_element = event.target
          }
        }
    
    0 讨论(0)
提交回复
热议问题