Access event.target in IE8 unobtrusive Javascript

前端 未结 4 1339
忘掉有多难
忘掉有多难 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: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');
    

提交回复
热议问题