在jQuery中更改DOM后,Click事件未触发

use*_*ksa 3 jquery jquery-click-event

我正在尝试在HTML页面中编写ADD&DELETE按钮来删除或添加页面中的图像代码.DELETE按钮将删除按钮前的第一个图像.ADD按钮将新图像插入HTML页面,删除按钮将插入图像.

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

这是代码:

<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>
Run Code Online (Sandbox Code Playgroud)

Roc*_*oC5 9

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

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

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

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