gpt4 book ai didi

jquery - jQuery 中 DOM 更改后,单击事件未触发

转载 作者:行者123 更新时间:2023-12-01 00:35:04 26 4
gpt4 key购买 nike

我正在尝试在 HTML 页面中编写“添加和删除”按钮来删除或添加页面中的图像代码。 DELETE 按钮将删除该按钮之前的第一张图像。 ADD 按钮将在 HTML 页面中插入新图像,而删除按钮将在图像中插入。

该代码工作正常:单击“删除”按钮时删除图像,单击“添加”按钮时插入图像。问题是:单击“添加”按钮后插入的删除按钮不起作用。因此,如果您单击“添加”按钮,然后单击“删除”按钮,图像将不会隐藏;单击事件未触发。

这是代码:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$('.img-post input').after('<button type="button" >Delete</button>');

$(".img-post button").click(function() {
$(this).prev().prev().remove();
$(this).prev().remove();
$(this).remove();
});

$(".add-img button").click(function() {
$('<img src="image3.jpg" /><input type="hidden" name="allimages[]" value="image3.jpg" /><button type="button" >Delete</button><br />').appendTo('.img-post');
});

});


</script>
</head>
<body>
<div class="img-post">
<img src="image1.jpg" /><input type="hidden" name="allimages[]" value="image1.jpg" /><br />
<img src="image2.jpg" /><input type="hidden" name="allimages[]" value="image2.jpg" /><br />
</div>

<div class="add-img">
<button type="button" >Add image</button>
</div>

</body>
</html>

最佳答案

使用 live() 而不是 click() 将事件处理程序绑定(bind)到按钮的单击事件:

$(".img-post button").live('click', function() {
$(this).prev().prev().remove();
$(this).prev().remove();
$(this).remove();
});

这将确保在初始 DOM 加载后添加的与您的选择器匹配的所有按钮也将触发相同的功能。

http://api.jquery.com/live/

关于jquery - jQuery 中 DOM 更改后,单击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7669875/

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