2013-10-21 34 views
1

我應該在這些類型的情況下使用addEventListener我應該使用addEventListener

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

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

,爲什麼?

+0

如果從IE8要支持和下面,你將不得不使用「填充工具」來添加的addEventListener支持。谷歌的「addEventListener polyfill」可以找到人們爲此做出的解決方案。 – Frug

回答

3

onchange屬性要求fun函數在全局範圍內。在一個更大的應用程序中,您希望避免這種情況,因爲可能會有來自應用程序或外部庫的具有相同名稱的其他函數。或者想象一下在頁面上構建多次使用的組件。

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(); 
    }); 
); 
+1

加'addEventListener'可以添加多個事件,而不必擔心忘記傳遞'this'或'event'等等。而且,無論如何,[Unobtrusive JavaScript](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript)優先於內聯處理程序:-) –