有谁知道为什么upload.onprogress在单独函数中无法正常工作?xmlhttprequest在函数中无法正常工作
代码正常工作(进度条缓慢移动):
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progress.value = (e.loaded/e.total) * 100;
}
};
,但如果我把它改成功能,它不工作了:
xhr.upload.onprogress = uploadProgress(event);
function uploadProgress(e) {
if (e.lengthComputable) {
progress.value = (e.loaded/e.total) * 100;
}
}
在第二个代码,进度在上传文件完成上传后,直接跳到100%,上传时很好地移动到100%
所以,我试过提供的解决方案,它实际上工作,如果我把里面的功能。有没有办法把它放在功能之外?
function uploadFile(blobFile, fileName) {
...
...
// Listen to the upload progress for each upload.
xhr.upload.onprogress = uploadProgress;
// Progress Bar Calculation why it has to be in uploadFile function..
function uploadProgress(e) {
if (e.lengthComputable) {
progress.value = (e.loaded/e.total) * 100;
}
}
uploaders.push(xhr);
xhr.send(fd);
}
//it does not work if I put it outside the function. is there anyway to do this?
function uploadProgress(e) {
if (e.lengthComputable) {
progress.value = (e.loaded/e.total) * 100;
}
}
你是对的..变量进步是uploadFile()内。这就是为什么它不起作用。在JavaScript中有没有什么好的做法,而不是将它作为一个函数内部的函数..这在某种程度上看起来很糟糕。因为 var progress = document.createElement('progress'); 应位于uploadFile()内部,因此每次调用时都会生成多个进度栏。因此,我不能让它成为全局变量var – Harts 2012-03-14 19:06:06
@ user1096900您可以使用匿名函数:'xhr.upload.onprogress = function(e){}'或者只是一个匿名包装函数:'xhr.upload.onprogress = function(e ){uploadProgress(e,progress);}'。 – ComFreek 2012-03-14 19:11:44