同一个jquery可以在一个页面上显示多个图像上传按钮

时间:2018-05-10 05:00:17

标签: javascript php jquery

我使用PHP表单,其中我想提交带有许多图像上传按钮的表单。 在我的页面中有很多多个上传按钮。我想对所有具有不同名称和ID的多个图像上传按钮使用相同的jquery。

我的代码是:

  <input type="file" id="files" name="dog_img[]" class="upload-img" onchange="readURL(this);" multiple>

   <input type="file" id="files1" name="dog_img1[]" class="upload-img" onchange="readURL(this);" multiple>

   <input type="file" id="files2" name="dog_img2[]" class="upload-img" onchange="readURL(this);" multiple>

  <input type="file" id="files3" name="dog_img3[]" class="upload-img" onchange="readURL(this);" multiple>

Jquery代码是:

     $(document).ready(function() {
     $('.upload-img').change(function () {
     var co =0;
     var len =5;

   for (var i=0; i < len; i++)
   {



   (function (j, self) 
    {

     var reader = new FileReader()
     reader.onload = function (e) {
     var image = new Image();
     image.src = e.target.result;
     image.onload = function () {
     var height = this.height;
     var width = this.width;
      if (height < 700 || width < 1000) {
       alert("Height and Width must not exceed 1024px.");
      return false;
   }
  };
   co++;
  $('.gallery-row').append('<div class="col-md-2" id="pip">
   <span id="'+[co]+'" data-id="'+[co]+'" class="click-form">
     <img class="imageThumb" src="' + e.target.result 
     + '"/>' + '</span><span data-id="'+[co]+'" class="remove">X
       </span></div>');

}

    reader.readAsDataURL(self.files[j])
    })
    (i, this);
   }

   });
  });

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,您将获得文件长度

        $(document).ready(function() {
     $('.upload-img').bind('change',function () {
     var co =0;
     var len =5;
         var num_of_images =  this.files.length;
        alert(num_of_images);
       for (var i=0; i < len; i++)
       {

       (function (j, self) 
        {

         var reader = new FileReader()
         reader.onload = function (e) {
             var image = new Image();
             image.src = e.target.result;
             image.onload = function () {
       console.log("image",image);
             var height = this.height;
             var width = this.width;
              if (height < 700 || width < 1000) {
               alert("Height and Width must not exceed 1024px.");
              return false;
           }
          };
           co++;
              $('.gallery-row').append('<div class="col-md-2" id="pip">            <span id="'+[co]+'" data-id="'+[co]+'" class="click-form">                <img class="imageThumb" src="' + e.target.result + '"/>' + '</span><span data-id="'+[co]+'" class="remove">X </span></div>');
            reader.readAsDataURL(self.files[j])
            }


        })
        (i, this);
       }

       });
  });

fiddle link

我更改了此var num_of_images = this.files.length;而不是var num_of_images = $(".upload-img")[0].files.length;

更新小提琴

updated fiddle link