gpt4 book ai didi

javascript - .change 事件仅在第一次触发

转载 作者:行者123 更新时间:2023-11-28 01:16:46 26 4
gpt4 key购买 nike

我试图在每次文件输入更改时触发更改事件,现在我每次都试图清除该值,第一次它有效,但是当用户第二次更改文件字段时,readURL(input) 不运行..为什么?

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('input') 但这不会触发,

最佳答案

您需要event delegation当你改变 DOM 时:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

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

关于javascript - .change 事件仅在第一次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23742159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com