【问题标题】:Image upload script to be more dynamic图片上传脚本更加动态
【发布时间】:2014-12-18 15:38:23
【问题描述】:

我有一个工作脚本,它显示用户想要上传的图像的预览,该脚本适用于单个图像上传。我现在要在多张图片上传时使用这个脚本,并希望脚本中的 readURL 函数动态工作,所以我不必重复这些行

 $("#patient_pic1").live("change",function(){
        readURL(this, "#preview_image1")
     });

对于每个上传容器

这是我的html

<div class="upload-file-container"> <img id="preview_image1" class="preimg" src="#" alt="" />
  <input type="file"  id="patient_pic1" name="pic[]" class="photo" />
</div>
<div class="upload-file-container"> <img id="preview_image2" class="preimg" src="#" alt="" />
  <input type="file"  id="patient_pic2" name="pic[]" class="photo" />
</div>

和 Jquery

function readURL(input, target) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            var image_target = $(target);
            reader.onload = function (e) {
                image_target.attr('src', e.target.result).show();
            };
            reader.readAsDataURL(input.files[0]);
         }
     }

          $("#patient_pic1").live("change",function(){
    readURL(this, "#preview_image1")
 });
       $("#patient_pic2").live("change",function(){
readURL(this, "#preview_image2")
 });

http://jsfiddle.net/6j1kr549/1/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你可以这样做:

     $('input[type="file"]').on("change",function(){
         var target = '#'+$(this).parent().find('img').attr('id');
        readURL(this, target);
     });
    

    WORKING DEMO

    【讨论】:

    • 不错,但是会得到任何类型“文件”的控制权,用IF语句会更好。
    • 是的,但这就是用户想要包含所有“文件”类型的内容。
    • 可以通过 .upload-file-container input[type="file"] 或 .upload-file-container .photo 定义范围。因为他想要上传部分的所有文件输入?我猜不是整个页面。
    【解决方案2】:

    您应该使用 each() 函数来循环所有具有相同名称的类并获取类中每个元素的输入控件: PD:计数器是为了澄清,但很实用:

    var counter = 1;
    $('.upload-file-container').each(function() {
        $(this, "#patient_pic" + counter.toString()).live("change",function(){
            readURL(this, "#preview_image" + counter.toString())
         });
         counter = counter + 1;
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 2013-07-22
      相关资源
      最近更新 更多