文件上的 JavaScript for 循环 FileReader

2024-04-20

问题让我心碎。有人能帮我吗? 在里面<script>我的 html 文件中的标签我有这个:

window.ondragover = function(e){return false;}
window.ondragenter = function(e){return false;}
window.ondrop = function(e){
    var files = e.target.files || e.dataTransfer.files;
    for (var i = 0, file; file = files[i];i++){
        var img = document.createElement('img');
        img.height = 200;
        img.width = 200;
        img.style.background = 'grey';
        document.body.appendChild(img);
        var reader = new FileReader();
        reader.onload = function(){
            img.src = reader.result;
        }
        reader.readAsDataURL(file);
    }
    return false;
}

但是当我在浏览器上放置多个图像文件时,只有最后一个图像文件被加载并显示在最后一个 img 元素中,其他图像文件保持灰色。


正如@chazsolo 提到的:

有一种感觉,这将是由于您在循环中使用了 img 造成的。由于 reader.onload 是异步的,因此 for 循环已经完成,并且 img 指向最后一个

您可以使用以下方法修复此问题let代替var在循环内(让-MDN) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let。这将给每个img and reader循环内的块作用域,允许异步读取器方法仍然访问该特定循环运行的实际值。

window.ondragover = function(e){return false;}
window.ondragenter = function(e){return false;}
window.ondrop = function(e){
    var files = e.target.files || e.dataTransfer.files;
    debugger;
    for (var i = 0, file; file = files[i];i++){
        let img = document.createElement('img');
        img.height = 200;
        img.width = 200;
        img.style.background = 'grey';
        document.body.appendChild(img);
        let reader = new FileReader();
        reader.onload = function(){
            img.src = reader.result;
        }
        reader.readAsDataURL(file);
    }
    return false;
}

更新:var 与 let

那么为什么它没有像怀疑的那样工作var? 我尝试解释一下两者的区别let and var一些实际的例子。

变量声明,无论它们出现在哪里,都会在任何变量声明之前进行处理 代码被执行。

这导致我们看到以下示例(不要介意最后的错误,该错误是由片段插件产生的):

用 var 声明

/**
In this example, 'a' is declared after it is used. This doesn't matter, as the 
declaration of 'a' will be processed before running the code. This means a is 
initialized with 'undefined' but is valid. Also the scope of a lies within the 
execution context, that's why it is even available outside of the loop. 
**/
console.log("---------");
console.log("Example Declaration var");
console.log("---------");
for (var i = 0; i < 2; i++) {
  console.log(a); // a is declared but undefined on the 1st run, afterwards it get redeclared and owns the value from the last run.
  var a = i;
}
console.log(a); // a is even available out here as still same execution context.
We see, that on every re declaration of a the value of the a before, is kept. It is not a new "instance".

那么如果我们在循环中使用异步函数会发生什么?

带 var 的异步函数

/**
This example shows you the effects, if you use a async function within a loop. 
As the loop will be executed way under 100 miliseconds (which is the time out 
of the async function), c will have the same value for all exections of the 
async mehtod, which is the value assigned by the last run of the loop.
**/
console.log("---------");
console.log("Example effects async var");
console.log("---------");
for (var i = 0; i < 2; i++) {
  var c = i;
  setTimeout(function() {
    console.log(c); //var does redeclare, therefor c will be modified by the next loop until the last loop.
  }, 100);
}

完全相同,始终相同的输出(适应您的问题,始终相同的 img 元素和文件)

让我们看看发生了什么let

用 let 声明

/**
In this example, 'b' is declared after it is used with let. let will be processed 
during runtime. This means 'b' will not be declared when used. This is an invalid 
state. let will give a strict context within the loop. It will be not available 
outside. let has a similar behavior as a declaration in Java.
**/
console.log("---------");
console.log("Example Declaration let");
console.log("---------");
for (var i = 0; i < 2; i++) {
  try {
    console.log(b); //b is not declared yet => exception
  } catch (ex) {
    console.log("Exception in loop=" + ex);
  }
  let b = i;
  console.log("Now b is declared:"+b);
}
try {
  console.log(b); // b is not available out here as the scope of b is only the for loop. => exception
} catch (ex) {
  console.log("Exception outside loop=" + ex);
}
console.log("Done");
A lots of exceptions are thrown, as let has a more specific scope. Which leads to more intentional coding.

最后,我们看看当我们使用时会发生什么let以及循环内的异步函数。

带 let 的异步函数

/**
This example shows you the effects, if you use a async function within a loop. 
As the loop will be executed way under 100 milliseconds (which is the time out 
of the async function). let declares a new variable for each run of the loop, 
which will be untouched by upcoming runs.
**/
console.log("---------");
console.log("Example effects async let");
console.log("---------");
for (var i = 0; i < 2; i++) {
  let d = i;
  setTimeout(function() {
    console.log(d); //let does not redeclare, therefor d will not be modified by the next loop
  }, 100);
}

结论

在你的例子中,你总是最终得到最后分配的img元素和最后分配的file。您执行相同操作的次数与数组中最后一个文件的文件数相同。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

文件上的 JavaScript for 循环 FileReader 的相关文章

  • 在 play 框架中将 javascript 变量转换为 scala

    我在 javascript 中有一些变量 var something 1 var url CSRF routes Some thing something 我在编译期间收到错误 因为 某物 换句话说 不引用 javascript 变量 编译
  • “新功能”的使用和性能问题

    我正在通过 AJAX 加载脚本文件 并运行其内容 我这样做 new Function someargument xhr responseText somevalue 然而 根据 MDN 的说法 Function使用创建的对象Function
  • 纯函数可以异步吗?

    在浏览纯函数的定义时 它通常定义有两个特征 1 给定相同的输入应该产生相同的输出 2 不应产生任何副作用 这是否也意味着纯函数不应该是异步的 如果不是 怎么会这样 如果是的话 我很想看到 JavaScript 中异步纯函数的一些示例 是的
  • JavaScript中有字符串池的概念吗?我们可以获取仅引用一个 String 对象的值/键吗?

    我有一个大型 json 映射 其中包含大约 100 万个对象 每个对象包含大约 200 个键值对 例如 key1 val1 key2 val2 key1 val3 key2 val4 正如您所看到的 键在这里被重复 每个键都意味着一个新的
  • 在不同窗口的上下文中执行函数?

    假设顶部窗口中有一个功能 例如 function z alert window name 我们还假设该文档中有一个 iframe 同源 顶部窗口中的函数是否可以在另一个窗口的上下文中执行此函数 以便它显示 iframe 的名称而不是顶部窗口
  • 通过排队预加载图像?

    我正在寻找一种预加载特定图像并将其添加到队列中的方法 这是我目前所处的位置 http shivimpanim org testsite imageloader html http shivimpanim org testsite image
  • 打字稿地图迭代失败

    我正在使用下面的函数来比较两个地图 有趣的是 for 循环内的代码永远不会被执行 所以 console log key val 代码永远不会被执行 当然 我确保我正在比较的映射不为空并且大小相同 以强制执行 for 循环内的代码 我犯了一个
  • ionic 2 从 json 填充选择选项

    我正在尝试动态填充ion select带有 json 对象的下拉列表 我的 html 组件如下所示
  • 如何使用 JS 和 Chrome 控制台向频道发送 Discord 消息?

    如何使用 JS 和 Chrome 控制台在不使用 Discord API 的情况下将 Discord 消息发送到 Discord 频道 看来这是不可能的事了 打开不和谐控制台 ctrl shift i 不起作用 请参阅下面的编辑 然后进入网
  • 如何在 d3.scale.ordinal() 中指定域?

    var W 100 var H 200 var data v 4 v 8 v 15 v 16 v 23 v 42 var x d3 scale linear domain 0 max x range 0 W var y d3 scale o
  • Redux 中的排队操作

    我目前遇到的情况是我需要连续运行 Redux Actions 我看过各种中间件 比如 redux promise 看起来不错如果您知道触发根操作 由于缺乏更好的术语 时的连续操作是什么 本质上 我想维护一个可以随时添加的操作队列 每个对象在
  • 解码URIComponent抛出错误“URI格式错误”

    As unescape已被弃用 我已选择decodeURIComponent 但它没有按预期工作 decodeURIComponent无法解码以下 URI 组件 Coast 20Guard 20Academy 20to 20hold 20a
  • 如何让 ckeditor 停止删除空 div

    stackoverflow 上也有类似的问题 但这些问题的答案对我不起作用 所以请不要将其标记为重复 在我的 cms 中 我希望人们能够添加 SPA 单页应用程序 内容页面 此类应用程序通常只有一个具有某些属性的 div 并且使用 java
  • 如何访问打字稿中的组件

    我有一个基本的 Angular 应用程序 如下所示 app component html h1 Test Umgebung h1 div div
  • Javascript,检测触摸设备

    我正在使用此函数来检测设备是否是触摸设备 function is touch device return ontouchstart in window onmsgesturechange in window 从这里得到这个功能 使用 Jav
  • PHP/Web 脚本保护

    我想用 PHP 和 javascript 编写一个脚本 并以某种方式保护我的源代码 以便我可以出售我的脚本 我正在寻找如何保护我的脚本的想法 如果我将其出售给某人 我如何阻止该人将其作为他们的产品重新分发 我知道有ZEND和ionCube
  • 在 JavaScript 中,将 NodeList 转换为数组的最佳方法是什么?

    DOM 方法document querySelectorAll 和其他一些 返回一个NodeList 对列表进行操作 例如使用forEach the NodeList必须首先转换为Array 转换的最佳方式是什么NodeList to an
  • 如何使用ajax从服务器接收返回的数据?

    基本上我有一个带有用户名文本框和提交按钮的表单 现在我想要的是 当用户在文本框中输入文本时 它应该获取文本框值并将用户名发送到服务器 以便服务器可以检查该用户名是否被任何其他用户占用 我可以将文本值发送到服务器 但我不知道如何接收回一些数据
  • AngularJs 位置路径更改,无需重置所有控制器

    我的问题的简短版本是 如何更改 URL 而不需要触发路由更改或不需要运行当前显示页面上的所有控制器 Details 我有一个模板 显示在
  • setInterval 会导致浏览器挂起吗?

    几年前 我被警告不要使用setInterval很长一段时间 因为如果被调用的函数运行时间超过指定的时间间隔 可能会导致浏览器挂起 然后无法跟上 setInterval function foo bar i 1 现在 我知道在循环中添加大量代

随机推荐