我在嘗試刪除重複的JavaScript代碼。我有一個頁面有很多<input type="file">
。每個加載一個圖像並執行一些獨特的處理。問題是,我有以下代碼的很多重複:如何刪除DOM事件處理程序的重複JavaScript代碼?
inputFile1.onchange = function (e) {
var file = e.target.files[0];
if (typeof file == 'undefined' || file == null) {
return;
}
var imageType = /image.*/;
if (!file.type.match(imageType)) {
window.alert('Bad file type!');
return;
}
var reader = new FileReader();
reader.onloadend = function (e) {
var imageLoader = new Image();
imageLoader.onload = function() {
// process image
};
imageLoader.src = e.target.result;
};
reader.readAsDataURL(file);
};
inputFile2.onchange = ... (repeats all but process image)
inputFile3.onchange = ... (repeats all but process image)
只有在process image
註釋代碼變化。我如何刪除周圍的重複代碼?
我知道JavaScript函數是對象。我如何定義一個函數對象併爲每個事件處理程序創建一個不同的實例,並將process image
的不同函數傳遞給每個對象?
無需使用返回函數的函數。只需將onchange分配給常用功能即可。 – jfriend00 2012-08-05 21:37:31
@ jfriend00仍然需要一種將非公共函數與'input [type =「file」]關聯的方法。 – Dennis 2012-08-05 21:44:50
咦?你可以從'e'參數中得到引發該事件的對象,並且我沒有看到你在額外的功能級別上做了額外的事情。它看起來並不需要我。 – jfriend00 2012-08-05 21:49:54