adding event as parameter within function, using addEventListener (Doesn't work in FF/IE). Javascript

后端 未结 2 2125
滥情空心
滥情空心 2021-02-08 21:56


FML



        
相关标签:
2条回答
  • 2021-02-08 22:35

    In some browsers like Firefox the event has to be passed as a parameter, so you have to replace this code

    div.addEventListener("mousemove", function(){test(event, this)}, true);
    

    with this

    div.addEventListener("mousemove", function(event){test(event, this)}, true);
    

    Compare carefully the two lines of code and notice the event property passed as parameter of the function added into the second row.

    for old IE ver attachEvent() has to be used;

    div.attachEvent("onclick", function(event){test(event, this)});
    

    Notice that attachEvent has been replaced in modern standard js with addEventListener and now almost all modern browser support that.

    Here http://caniuse.com/#feat=addeventlistener is possible to see compatibility table.

    0 讨论(0)
  • 2021-02-08 22:40
    div.addEventListener("mousemove", function(){test(event, this)}, true);
    

    Well, of course you get "event is undefined" ! When the mousemove event triggers, your event handler is called:

    function(){test(event, this)}
    

    There are two ways to reach the event information object. Either it is passed to the event handler as an argument, or it can be found in window.event.

    Suppose the second case holds. As there is no local variable named event in your function, nor is there such variable in function1 that calls it, the browser looks if there is an event defined in the global object. In JavaScript, the global object is called window, so your function is interpreted as

    function(){test(window.event, this)}
    

    and it works.

    However, as I noted before, in some browsers, the event information is passed in the argument. So your event handler probably wanted to look like this:

    function(event){test(event, this)}
    

    otherwise the event passed to test() would be undefined. So, this is how to make a cross-browser handler:

    function(event) {
      if (!event) // i.e. the argument is undefined or null
          event = window.event;
    
      test(event, this);
    }
    

    The second problem is that addEventListener() doesn't work in older IEs (it does in IE9, though). For older IEs, you have to use a similar function called attachEvent(). Or, if you only attach one handler, you can do it the simple way

    div.onmousemove = function() {...};
    
    0 讨论(0)
提交回复
热议问题