有人知道为什么upload.onprogress在单独的函数上不能正常工作吗?
代码正常工作(进度条缓慢移动):
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;
}
}
答案 0 :(得分:6)
使用uploadProgress(event);
调用函数本身并将返回值赋给xhr.upload.onprogress
,而不是将其指定为回调函数:
xhr.upload.onprogress = uploadProgress;
答案 1 :(得分:1)
在第二个例子中,你应该使用
xhr.upload.onprogress = uploadProgress;
不
xhr.upload.onprogress = uploadProgress(event);
您已分配调用函数的结果,而不是对函数的引用。
答案 2 :(得分:1)
在分配回调之前如何定义函数? JavasCript有时在以后定义函数时会遇到问题。
我的意思是你可以替换:
// Listen to the upload progress for each upload.
xhr.upload.onprogress = uploadProgress;
// Progress Bar Calculation
function uploadProgress(e) {
if (e.lengthComputable) {
progress.value = (e.loaded / e.total) * 100;
}
}
与
// Progress Bar Calculation
function uploadProgress(e) {
if (e.lengthComputable) {
progress.value = (e.loaded / e.total) * 100;
}
}
// Listen to the upload progress for each upload.
xhr.upload.onprogress = uploadProgress;