输入[类型文件]更改后,变量imageLen不重置

时间:2015-11-28 11:42:01

标签: javascript jquery html variables reset

我有这段代码给我带来了问题......



    "use strict";
    $(document).ready(function() {
      $(".mylbl").click(function() {
        var imageslen, imagesSize, imagesName; //decleartion variale
        //Intiallize variables for prevent to upload many time images
        imageslen = imagesSize = imagesName = 0;
        $(".inputfile").click();
        $(".inputfile").change(function() {
          imageslen = 0;
          var uploadedImages = $(".inputfile")[0].files;
          imageslen = uploadedImages.length;
          imagesSize = [];
          imagesName = [];
          for (var i = 0; i < imageslen; i++) {
            imagesSize[i] = uploadedImages[i].size;
            imagesName[i] = uploadedImages[i].name;
            console.log(imagesSize[i]);
            console.log(imagesName[i]);
          }
        });
      });
    });
&#13;
body {
  margin: 0px;
  padding: 0px;
  background-color: #ccc;
  color: #f4f9c4;
  width: 100%;
  height: 100%;
}
form {
  box-sizing: border-box;
  border: 10px solid #fff;
  width: 250px;
  height: 300px;
  margin: auto;
  padding: 20px;
}
.mylbl {
  box-sizing: border-box;
  text-align: center;
  display: block;
  min-width: 80px;
  height: 50px;
  background-color: #ff4500;
  line-height: 300%;
  border: 5px solid #C33100;
  border-radius: 10px;
  cursor: pointer;
}
.inputfile {
  display: none;
}
.btn {
  width: 200px;
  height: 70px;
  background-color: #129EA4;
  border: none;
  border: 5px solid #fff;
  border-radius: 10px;
  margin: 10px 10px;
  cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form class="myform" method="post" id="myform" enctype="multipart/form-data">
  <input type="file" name="album" name="gallry[]" multiple class="inputfile" />
  <label for="imgrs" class="mylbl">Please Choose Images..</label>
  <input id="_d11re" type="button" name="addimagedata" value="Upload" class="_p25ed btn" />
</form>
&#13;
&#13;
&#13; 在运行此代码之前打开浏览器的控制台..检查问题并上传超过3个以上的四个时间图像

问题是在js代码中变量imageslen没有重置..当我第一次上传图像时,代码工作正常,当我第二次点击该labal时(&#34;请选择图像&#34;)上传图片图片上传但两次.. 在这里,我展示了我的谷歌镀铬的小图像.. enter image description here

1 个答案:

答案 0 :(得分:1)

每次点击mylbl时,新的Change EventListener都会绑定到inputfile

$(".mylbl").click(function() {
    $(".inputfile").click();
    // move the rest of the function from HERE
}
// to HERE

如果您有任何问题,请使用jsFiddle或其他内容向我们展示您的中间结果。