订单问题附加在文件阅读器中

时间:2013-11-04 22:53:58

标签: javascript jquery filereader

我有一个Jquery函数,它读取FilesList并在IMG html对象中显示图像。

function load_images(files) {
    for (var i = 0; i < files.length; i++) {
        // Validate the image type
        if(validate_file(files[i])) {
            var reader = new FileReader();
            reader.onload = function(e) {    
                $(".upload_thumbnails").append(render_thumb(e.target.result, i)); // Return a string with the img object
            };
        } 
        reader.readAsDataURL(f);
    } 
}

但是我的图像没有按照fileList的顺序添加。 fileList(var文件)由多个输入文件html对象实现。

你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

方法readAsDataURL是异步的,意味着你的循环会产生很多加载数据的请求,但由于该方法是异步的,所以无法知道onload回调将以何种顺序叫做。这种行为是不确定的。

这可以通过将所有元素与其索引一起存储在数组中来解决,然后在完全加载所有图像时实际渲染出来。

另一种方法是在请求启动时创建占位符div,并在onload回调的闭包中捕获它。然后你可以将图像附加到该div,这将导致你想要的行为。

像这样:

function load_images(files) {
    for (var i = 0; i < files.length; i++) {
        // Validate the image type
        if(validate_file(files[i])) {
            var reader = new FileReader(),
                div    = $("<div></div>");
            $(".upload_thumbnails").append(div);            

            reader.onload = function(e) {    
                div.append(render_thumb(e.target.result, i)); // Return a string with the img object
            };
        } 
        reader.readAsDataURL(f);
    } 
}