Can multiple event listeners/handlers be added to the same element using javascript?

后端 未结 3 1741
小蘑菇
小蘑菇 2020-11-29 04:47

I have:

if (window.addEventListener) {
  window.addEventListener(\'load\',videoPlayer,false);
}
else if (window.attachEvent) { 
  window.attachEvent(\'onload         


        
3条回答
  •  臣服心动
    2020-11-29 04:59

    You can do how ever you want it to do. They don't have to be together, it depends on the context of the code. Of course, if you can put them together, then you should, as this probably makes the structure of your code more clear (in the sense of "now we are adding all the event handlers").

    But sometimes you have to add event listeners dynamically. However, it is unnecessary to test multiple times whether you are dealing with IE or not.

    Better would be to abstract from this and test only once which method is available when the page is loaded. Something like this:

    var addEventListener = (function() {
        if(document.addEventListener) {
            return function(element, event, handler) {
                element.addEventListener(event, handler, false);
            };
        }
        else {
            return function(element, event, handler) {
                element.attachEvent('on' + event, handler);
            };
        }
    }());
    

    This will test once which method to use. Then you can attach events throughout your script with:

    addEventListener(window, 'load',videoPlayer);
    addEventListener(window, 'load',somethingelse);
    

提交回复
热议问题