Firefox “window.event is undefined” error

后端 未结 7 1378
悲哀的现实
悲哀的现实 2020-12-03 11:38

I have this script:

function postBackByObject(e) {
   var o = window.event.srcElement || e.target;
   if (o.tagName == \"INPUT\" && o.type == \"check         


        
相关标签:
7条回答
  • 2020-12-03 12:00

    It's possible to pass event object in the inline declaration:

    <input type="button" onclick="postBackByObject(event);" value="click" />
    
    function postBackByObject(e) {
        var o = e.srcElement || e.target;
        // ...
    }
    
    0 讨论(0)
  • 2020-12-03 12:06

    i am not sure if window.event is supported in all browsers. I think you get event in variable "e" of postBackByObject(e)

    0 讨论(0)
  • 2020-12-03 12:08

    Your line

    var o = window.event.srcElement || e.target;
    

    fails on all browsers excepting IE, since for them windows.event is undefned

    The proper formulation would be :

    var o = e ? e.target : window.event.srcElement;
    

    Since standard compliant browsers will pass the event as the parameter e and the target at e.target in IE, e will be undefined and you must use window.event.srcElement

    Note that recent versions of IE do support the standards compliant model.

    On a more generic note, when you try and access a value as a.b.c.d then a.b.c must be a defined object else you will get the error a.b.c undefined.

    0 讨论(0)
  • 2020-12-03 12:09

    That's because it is. window.event is for older versions of IE.

    The typical way to do this is:

    function postBackByObject(e) {
        e = e || window.event;
        var o = e.srcElement || e.target;
        // ...
    }
    
    0 讨论(0)
  • 2020-12-03 12:14

    Pass the event on the onClick event like this:

    onclick="myCustomFunction(event);"

    It does work and you can access the event object!

    0 讨论(0)
  • 2020-12-03 12:15

    You are attaching events inline onclick="postBackByObject();"

    Try passing this(the event target) to onclick="postBackByObject(this);" Modify your function to handle this change:

    function postBackByObject(e) {
       if (e.tagName == "INPUT" && e.type == "checkbox") {
            __doPostBack("", "");
        }
    }
    

    A better alternative will be to attach events using addEventListener

    If your markup looks like:

    <div id="TvCategories" onclick="postBackByObject(this);" />
    

    then

    document.getElementById('TvCategories').addEventListener('click', postBackByObject);
    

    Your postBackByObject function remains unchanged when using this approach.

    0 讨论(0)
提交回复
热议问题