在文件读取器中追加的订单问题

Order issue with append in a file reader

本文关键字:单问题 问题 读取 文件 追加      更新时间:2023-09-26

我得到了一个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);
    } 
}

但是我的图像没有按文件列表的顺序追加。文件列表(var 文件)由多输入文件 html 对象实现。

你有什么想法吗?

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