2016-10-30 4 views
0

私のページにはいくつかの入力タイプのファイルがあり、ファイルのサイズを与える関数を実行したいと思います。 ファイルタイプのサイズを取得する機能はありますが、この同じ機能を他の入力タイプエレメントに呼び出す方法があるのだろうかと思います。javascript内のすべてのファイル入力タイプの実行関数

私はそれを持っているので、私はそれのための新しい機能を作成する必要があります。 これは、あなたはすべての入力のイベントリスナーと同じ機能を追加することができ、私のJSbin

<input type="file" name="someName" id="uploadID" /> 
<input type="file" name="someName" id="uploadID2" /> 
<input type="file" name="someName" id="uploadID3" /> 

var el = document.getElementById('uploadID'); 
el.onchange = function(){ 
    var input, file; 

    if (!window.FileReader) { 
     alert("The file API isn't supported on this browser yet."); 
     return; 
    } 

    input = document.getElementById('uploadID'); 
    if (!input) { 
     alert("p", "Um, couldn't find the fileinput element."); 
    } 
    else if (!input.files) { 
     alert("This browser doesn't seem to support the `files` property of file inputs."); 
    } 
    else if (!input.files[0]) { 
     alert("Please select a file before clicking 'Load'"); 
    } 
    else { 
     file = input.files[0]; console.log(file); 
     alert("File " + file.name + " is " + file.size + " bytes in size"); 
    } 
}; 

答えて

1

です。イベントリスナーでは、リスナーが追加された要素を参照できるため、入力ごとに新しいものを作成する必要はありません。thisを使用します。

var els = document.querySelectorAll('input'); 
[].forEach.call(els, function(el) { 
    el.addEventListener('change', listener); 
}); 
function listener() { 
    if (!window.FileReader) { 
    alert("The file API isn't supported on this browser yet."); 
    return; 
    } 
    var input = this; 
    if (!input.files) { 
    alert("This browser doesn't seem to support the `files` property of file inputs."); 
    } else if (!input.files[0]) { 
    alert("Please select a file before clicking 'Load'"); 
    } else { 
    var file = input.files[0]; console.log(file); 
    alert("File " + file.name + " is " + file.size + " bytes in size"); 
    } 
} 
+0

ありがとう@Oriol – Diego

関連する問題