.change事件仅在第一次触发

时间:2014-05-19 15:54:48

标签: javascript jquery cordova

我试图在每次更改文件输入时触发更改事件, 现在我正在尝试每次都清除该值并且它第一次运行但是当用户更改文件字段时,readURL(输入)不运行的时间段为什么?

HTML

<input type='file' id="imgInp" onclick="readURL(input)" />

的javascript

$("#imgInp").change(function(){
             readURL(this);
             ClearFileUpload();
    });   

function readURL(input) {
      if (input.files && input.files[0]) {
      var reader = new FileReader();
      ClearFileUpload();
      reader.onload = function (e) {
      photo.innerHTML='<img src="' + e.target.result + '" width="400" />';
      }

      reader.readAsDataURL(input.files[0]);

       }
  }


function ClearFileUpload() {
     document.getElementById("photo").innerHTML="";
     var photo = document.getElementById('photo');
     var photoinput = document.getElementById('imgInp');
     if (photoinput != null) {
        document.getElementById('imgInp').outerHTML = photoinput.outerHTML;
    }
    document.getElementById("name").innerHTML="";
}

我尝试过.on('输入'),但这不会触发,

1 个答案:

答案 0 :(得分:1)

在更改DOM时需要event delegation

  

事件委托允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有后代触发,无论这些后代现在是存在还是将来添加。

$(document).on('change','#imgInp',function(){
         readURL(this);
         ClearFileUpload();
});