我如何显示多个图像? [英] How can I display multiple image?

查看:137
本文介绍了我如何显示多个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的html代码如下所示:

 < input type ='file'multiple /> 

我的javascript代码如下所示:

<$ ()函数(){
$(:file)。change(function(){
if(this.files&& this.files [0]){
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files [0]);
}
});
});

函数imageIsLoaded(e){
$('#myImg')。attr('src',e.target.result);
};

演示如下: https://jsfiddle.net/oscar11/ob8aas23/



当我上传一张图片时,会显示图片

但是当我上传超过1张图片时,只显示一张图片

我该如何解决这个问题?

解决方案

问题是只有一个 img 要显示的图像,将需要相同数量的 img 标签。因此,最好循环 files.length 并动态创建一个图片标签并添加源代码。

  $(function(){$(:file)。change(function(){if(this.files&& amp ; this.files [0]){for(var i = 0; i< this.files.length; i ++){var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files [ );}}});}); function imageIsLoaded(e){$('#myImg')。append('< img src ='+ e.target.result +'>');};  

< script src =https:// ajax。 googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script><input type ='file'multiple />< div id =myImg><<< ; / DIV>


My html code is like this :

<input type='file' multiple/>
<img id="myImg" src="#" alt="your image" />

My javascript code is like this :

$(function () {
    $(":file").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
        }
    });
});

function imageIsLoaded(e) {
    $('#myImg').attr('src', e.target.result);
};

Demo is like this : https://jsfiddle.net/oscar11/ob8aas23/

When I upload one image, it display the image

But when I upload more than 1 image, shown only one image

How can I solve this problem?

解决方案

The issue is there is only one img tag but for multiple images to be displayed , equal number of img tags will be required. So it will be better to to loop through the files.length and dynamically create a image tag and add source to it

$(function() {
  $(":file").change(function() {
    if (this.files && this.files[0]) {
      for (var i = 0; i < this.files.length; i++) {
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[i]);
      }
    }
  });
});

function imageIsLoaded(e) {
  $('#myImg').append('<img src=' + e.target.result + '>');
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' multiple/>
<div id="myImg">
</div>

这篇关于我如何显示多个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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