完成后如何调用函数(每个)(更改)

时间:2018-03-18 00:33:36

标签: javascript jquery

我试图在完成功能更改后调用(每个)。我的脚本添加了输入文件字段中的文件列表,我希望在完成example之后逐个显示这些文件。我的代码不起作用,我做错了什么?

$('.drop-input').on('change', function(){
    /* ... */
    var data = $(this)[0].files;
    $.each(data, function(index, file){
       var fRead = new FileReader();  
       fRead.onload = (function(file){  
          return function(e) {
              $('.append').append('<img src="'+e.target.result+'" class="drop-file" />');
          };
        })(file);
        fRead.readAsDataURL(file);
    
    });
    
    /* ... */

}).each('.drop-file',function(i) {
     $(this).delay(1000*i).fadeIn(1850);
});
.drop-file{
    width:100px;
    display:block;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" class="drop-input" multiple />
<div class="append"></div>

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题,其中最重要的是由以下代码引起的TypeError,这实际上使代码完全中断:

}).each('.drop-file',function(i) {
     $(this).delay(1000*i).fadeIn(1850);
});

您尝试对上述代码执行的操作可以轻松集成到为load事件设置的事件处理程序中。您只需要执行以下操作:

  • 在循环外创建一个计数器,该计数器将按每个加载的文件递增。
  • 使用display: none为创建的图片设置样式,因为在创建时,由于drop-file类的CSS规则,它已经可见。

<强>段:

&#13;
&#13;
/* ----- JavaScript ----- */
$('.drop-input').on('change', function() {
  /* Create a counter to use for the delay. */
  var counter = 0;
  
  /* Iterate over every file selected. */
  $.each(this.files, function(index, file) {
    /* Create a new file reader. */
    var fRead = new FileReader();
    
    /* Set the 'load' event. */
    fRead.onload = (function(file) {
      return function(e) {
        /* Create a new image and append it to the '.append' div. */
        var img = $("<img>", {
          "src": e.target.result,
          "class": "drop-file",
          "style": "display: none"
        }).appendTo(".append");
        
        /* Use the counter to fade the image in. */
        img.delay(1000 * counter++).fadeIn(1850);
      };
    })(file);
    
    /* Read the file as a data url. */
    fRead.readAsDataURL(file);
  });
});
&#13;
/* ----- CSS ----- */
.drop-file {
  width: 100px;
  display: block;
}
&#13;
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="drop-input" multiple/>
<div class="append"></div>
&#13;
&#13;
&#13;