我正在通过XmlHTTPRequest和HTML5上传多个文件。 我已经将上传工作正常,但我想为每个文件上传添加一个进度条。 但是,我目前的代码对于所有文件上传都使用最后一个进度条,而不是每个上传使用自己的进度条。 这在客户端主要是视觉效果,但它真的很让我烦恼。 我认为事件会覆盖自身并使用最后一个进度条,但原因不明。这是我的代码:
var files = event.dataTransfer.files;
// iterate over each file to upload, send a request, and attach progress event
for (var i = 0, file; file = files[i]; i++) {
var li = $("<li>" + file.name + "<div class='progressbar'></div></li>");
// add the LI to the list of uploading files
$("#uploads").append(li);
// fade in the LI instead of just showing it
li.hide().fadeIn();
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
var percent = parseInt(e.loaded / e.total * 100);
li.find(".progressbar").width(percent);
}, false);
// check when the upload is finished
xhr.onreadystatechange = stateChange;
// setup and send the file
xhr.open('POST', '/attachments', true);
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
}
我猜测 "progress" 事件没有正确地读取 "li"。我怀疑我需要做某种绑定来告诉 "progress" 事件使用特定变量作为它的 "li",但我不确定我缺少什么。