在javascript中运行所有文件输入类型的函数

时间:2016-10-30 03:06:58

标签: javascript html5

我的页面中有几个输入类型文件,想要运行一个给我文件大小的函数。 我确实有获取文件类型大小的函数,但我想知道是否有一种方法可以将这个函数调用到另一个输入类型元素。

我拥有它的当前方式,我将需要为它创建一个新功能而不想要它。 这是我的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 个答案:

答案 0 :(得分: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");
  }
}