DOM变化后事件绑定失效

时间:2023-03-10 02:40:43
DOM变化后事件绑定失效

第一个file在change时,是能够触发事件的,而第二插入的file则没有change事件。对于这个问题,有如下两种解决方法:

第一种是将绑定change事件封装成一个函数,在点击button按钮插入file控件之后,调用这个函数。如下:

<script type="text/javascript">
$(function(){
function fileChange(){
$('input[type ="file"]').change(function(){
console.log($(this).val())
if($(this).val() == ""){
alert("你好")
}
})
}
fileChange();
$('input[type ="button"]').click(function(){
$("#content").append('<input type="file"/>');
fileChange();
})
})
</script>

另一种方式,是在DOM加载之后和DOM内容发生改变时,绑定file控件的change事件,如下:

<script type="text/javascript">  

    window.onload,window.onchange = function(){
$('input[type ="file"]').change(function(){
console.log($(this).val() )
if($(this).val() == ""){
alert("你好")
}
})
} $('input[type ="button"]').click(function(){
$("#content").append('<input type="file"/>')
}) </script>