进度条不更新文件上传的宽度

progress bar not updating its width in file uploads

我正在上传文件并显示每次加载的进度条,但它只适用于一个进度条。

在html,

   <input type="file" id="file-input" multiple>
   <div id="file-list">
   </div>

在Javascript、

$('#file-input').change(function(e) {

for (var i = 0, f; f = files[i]; i++) {

    var reader = new FileReader();
    reader.readAsBinaryString(f);

    reader.onloadstart = function (e) {
      var text = '<div><div id="progress_bar" class="loading"><div class="percent">0%</div></div></div>';
      $('#file-list').append(text);
    }

    reader.onload = function(e) {
       var progress = document.querySelector('.percent');
       progress.style.width = '100%'; // replacing with percentage
       progress.textContent = '100%';
    }
 }

});

一次上传三个文件的结果显示一个进度条为 100%,两个进度条为 0%。这有什么问题吗?

您可以在 for 循环之外定义 f,调整 for 循环以包含条件 i < f.length ;将 i 传递给 IIFE,为每个对 FileReader.

的调用创建一个单独的作用域

$("#file-input").change(function(e) {
  var f = e.target.files;
  for (var i = 0; i < f.length; i++) {
    (function(n) {
      var reader = new FileReader();
      reader.readAsBinaryString(f[n]);

      reader.onloadstart = function(e) {
        var text = "<div><div class=loading><div class=percent-" 
                   + n + ">0%</div></div></div>";
        $("#file-list").append(text + "<br>");
      }

      reader.onload = function(e) {
        var progress = $(".percent-" + n);
        progress.css("width", "100%"); // replacing with percentage
        progress.text("100%");
      }
    }(i))
  }
});
[class^="percent"] {
  width: 1%;
  height: 24px;
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="file" id="file-input" multiple>
<div id="file-list">
</div>

另见