简体   繁体   English

我应该使用addEventListener

[英]should i use addEventListener

Should I use addEventListener in these type cases? 我应该在这些类型的情况下使用addEventListener吗?

<input id="input" type="file" onchange="fun()>

or 要么

document.getElementById("input").addEventListener("change", function() {
  fun();
});

and why? 为什么?

The onchange attribute requires the fun function to be in global scope. onchange属性要求fun函数在全局范围内。 In a larger application you want to avoid this, as there might be other functions with the same name from your application or from external libraries. 在较大的应用程序中,您希望避免这种情况,因为应用程序或外部库中可能存在具有相同名称的其他函数。 Or imagine building a component that is used several times on the page. 或者想象一下构建在页面上多次使用的组件。

addEventListener can be wrapped in a closure like this and be used inside an isolated component: addEventListener可以包装在这样的闭包中,并在隔离的组件中使用:

(function(){})(
    function fun(){
         // Now other components can also have a `fun` function, without causing confusion.
         // `fun` is only defined inside the IIFE (the (function(){})() wrapper around the module).
    }
    document.getElementById("input").addEventListener("change", function() {
      fun();
    });
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM