jQuery中的DOM更改后,未触发Click事件 [英] Click event is not firing after DOM changes in jQuery

查看:127
本文介绍了jQuery中的DOM更改后,未触发Click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对ADD& HTML页面中的DELETE按钮可在页面中删除或添加图像代码. DELETE按钮将删除该按钮之前的第一张图像. 添加"按钮会将新图像插入HTML页面,并将删除"按钮插入图像.

I am trying to code ADD & DELETE button in HTML page to delete or add images code in the page. The DELETE button will delete the first image before the button. The ADD button will insert a new image to HTML page and the delete button to the image.

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

The code works fine: it deletes the image when DELETE button is clicked and it inserts the image when ADD button is clicked. The problem is: the delete button that inserted after ADD button is clicked is not working. So if you click on ADD button and then click on DELETE button the image will not hide; the click event is not firing.

这是代码:

<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()将事件处理程序绑定到按钮的click事件:

Bind the event handler to the button's click event using live() instead of click():

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

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

This will ensure that all buttons which match your selector which are added after the initial DOM load will also fire the same function.

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

这篇关于jQuery中的DOM更改后,未触发Click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆