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

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


FML



        
2条回答
  •  不思量自难忘°
    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() {...};
    

提交回复
热议问题