jQuery 仅附加到现有对象

jQuery attaches only to Existing objects

我正在尝试创建一个按钮,onclick 会向页面添加一些新的 html 元素,但 jQuery 不会附加到新对象。

<script>
jQuery(document).ready(function(){
    jQuery("input[type='button']").click(function(){
        var ask=confirm('Are you sure');
        if(ask){
            var n=jQuery(this).parent();
            var s=jQuery(this).prop('id');
            n.html('Select Picture: <br><input type="file" name="'+s+'" id="'+s+'" required>');
            }
        }
    });
    jQuery(":file").change(function() {
        var na=jQuery(this).val();
        alert(na);
    });
});
</script>

现在这是该代码的 form 示例:

<form>
            <div><img src="image/source"><br>
            <input type="checkbox" required value="1" name="product1">image is ok<br>
            <input type="button" value="change image" id="product1" name="product1b"></div>
<input type="file" name="product2">
</form>

因此,当我单击 button 时,form 更改为:

<form>
<div>
Select Picture: <br>
<input type="file" name="product1" id="product1" required>
</div>
<input type="file" name="product2">
</form>

问题是 jQuery 函数 jQuery(":file").change(function() { 适用于 product2 但不适用于 product1,因为它在页面加载时不存在 jQuery没有附加到它。

当您的元素是动态的时,您必须使用委托事件:

jQuery(document).on('change', ':file', function(){
    // do stuff
});