Javascript error: TypeError: 'null' is not an object (evaluating 'event.target') on safari

前端 未结 3 910
长发绾君心
长发绾君心 2021-01-27 13:26

I have difficulty on integrating my JavaScript syntax. My code is working on Internet Explorer (IE). However, I encountered a JavaScript error when running it on Safari.

相关标签:
3条回答
  • 2021-01-27 13:57

    As Bhojendra mentioned don't use srcElement. Check for object null or not before accessing id or target property as below.

    document.onmouseup = function hideaddrspopup () 
    {   
    
    if (e && e.target && e.target.id!='fieldName')
      {   
        alert(e.target.id);
      }
    else if(e && e.srcElement && e.srcElement.id!='fieldName')
      {
        alert(e.srcElement.id);
      }
    }
    

    Updated with else if to support older IE browser. target should support it too but you could test without else part if it is necessary or not.

    0 讨论(0)
  • 2021-01-27 14:10

    According to MDN:

    This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

    Event.srcElement is a proprietary alias for the standard Event.target property. It is specific to old versions of Microsoft Internet Explorer.

    So just avoid using event.srcElement instead you should use event.target.

    0 讨论(0)
  • 2021-01-27 14:11

    You're missing the event variable in your function

    document.onmouseup = function hideaddrspopup (event) 
    {   
    
       if (event.srcElement.id != 'fieldName' || event.target.id != 'fieldName')
       {   
         alert(event.srcElement.id);
         alert(event.target.id);
       }
    }
    
    0 讨论(0)
提交回复
热议问题