在文件阅读器中追加的订单问题 [英] Order issue with append in a file reader

查看:93
本文介绍了在文件阅读器中追加的订单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got a Jquery function that read a FilesList and display in an IMG html object the image.

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(可变文件)是由多个输入文件html对象实现的.

But my images are not append in the sequential order of the fileList. The fileList (var files) is implement by an multiple input file html object.

你有什么主意吗?

推荐答案

方法readAsDataURL是异步的,这意味着您的循环将创建许多加载数据的请求,但是由于该方法是异步的,因此无法知道onload回调将以什么顺序被调用.该行为是不确定的.

The method readAsDataURL is asynchronous meaning that your loop will create a lot of requests to load data, but because the method is asynchronous there is not way to to know in which order the onload callback will be called. The behaviour is non-deterministic.

可以通过以下方式解决此问题:将所有元素及其索引存储在数组中,然后在完全加载完所有图像后实际渲染出所有图像.

This could be solved by storing all the elements in an array along with their index and then actually rendering out all the images when they have all loaded completely.

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

Another alternative is creating a placeholder div when the requests is started and capture it in the closure of the onload callback. Then you could append the image to that div, this would cause the behaviour you want.

像这样:

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);
    } 
}

这篇关于在文件阅读器中追加的订单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆