有誰知道爲什麼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