【问题标题】:Jquery Onload Function stopped for loop, passing for loop x inside functionJquery Onload 函数停止 for 循环,在函数内部传递 for loop x
【发布时间】:2015-01-04 23:09:02
【问题描述】:

我通过使用 dataTransfer

将图像文件从 XMLHttpRequest 传递到此函数 readfiles(files)

我要做的是在 reader.onload() 函数内的一行代码中同时预览图像和图像文件名。

因为将有超过 1 个文件传递给函数,我将它们放入 for 循环中

问题是当我尝试通过 readDataURL 预览图像时没问题,但我认为无法预览文件名是因为 reader.onload() 函数停止了for 循环从图像文件中循环。

这是我的代码

function readfiles(files) {

    var x;

    for(x = 0; x < files.length; x = x + 1) {

        var reader = new FileReader();
        reader.readAsDataURL(files[x]);
        reader.onload = function(e) {
            console.log(e.target.result);
            console.log(files[x].name);
        }   

    }
}

现在已经找了大约 5 个小时的解决方案,任何帮助!

【问题讨论】:

  • 你的控制台得到了什么?
  • 未捕获的类型错误:无法读取未定义的属性“名称”

标签: javascript jquery function for-loop filereader


【解决方案1】:

ROX 的回答是不对的。在他的例子中,你会看到它会输出相同的文件名 4 次。你需要的是一个闭包,它基本上会在每次迭代中保持正确的上下文。您可以按如下方式实现。检查小提琴http://jsfiddle.net/cy03fc8x/。

function readfiles(files) {
    for(x = 0; x < files.length; x = x + 1) {
        var file = files[x];
        (function(file){   //this is a closure which we use to ensure each iteration has the right version of the variable 'file'
            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function(e) {
                console.log(e.target.result);
                console.log(file.name);
            }
        })(file);          //on each iteration, pass in the current file to the closure so that it can be used within

    }
}

【讨论】:

  • 成功了! ..我找不到感谢你的方法,我真的很感谢你的帮助..你救了我,非常感谢!
  • 是的,你是对的,这里需要关闭,我也更新了我的答案以保持正确,还有 +1 :)
【解决方案2】:

因为onload 将稍后运行,所以此时x 比您的文件数多一。例如,如果您有 4 个文件,则在执行 onload 时,x 将是 5。

所以请保留对您当前文件的引用:

function readfiles(files) {
    for (var x = 0; x < files.length; x = x + 1) {
        // keep reference to current file on iteration
        var file = files[x];

        // create closure and execute it
        (function (file) {
            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function(e) {
                console.log(file.name);
            }
        }(file)); // pass the `file` to the function
    }
}

【讨论】:

  • 我将变量名保留在 onload 函数之外(复制并粘贴了您的代码),结果给了我相同的文件名 ex。 4次!喜欢 1.jpg | 1.jpg | 1.jpg ..等等!为什么会这样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多