如何将回调函数添加到由JQuery添加的元素

时间:2016-08-12 10:51:50

标签: jquery html

回调函数不适用于JQuery添加的元素。在我的示例中,有一个带有class=parent父div 。点击它后,正在添加<span class="child">Child</span>。但是,当我点击孩子时,它不会提醒消息。请参阅下面的示例

    <html>
    <head>
        <style>
            .parent{
                width: 50px;
                height: 30px;
                line-height: 30px;
                background-color: #232323;
                color: #fff;
                text-align: center;
            }

            .child{
                width: 50px;
                height: 30px;
                line-height: 30px;
                background-color: #f3b556;
                color: #232323;
                text-align: center;
                margin-top: 10px;
            }
        </style>
    </head>
    <body>
        <div class="parent">
            <span>Parent</span>
        </div>


        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $('.parent').click(function(){
                alert('parent clicked');
                $(this).after("<span class='child'>child</span>");
            });
            $('.child').click(function(){
                alert('child clicked');
            });
        </script>
    </body>
</html>

3 个答案:

答案 0 :(得分:0)

使用实时委派,因为.child是动态添加元素,正常事件侦听器不会在将来生成的子节点上注册click

$("body").on("click", ".child", function(){
    alert('child clicked');
});

答案 1 :(得分:0)

您可以从父级委派事件。

当你创建一个新对象时,它缺少可以添加到其他元素之前的事件监听器,它与它的同一个类。

但是,如果将侦听器添加到现有的不可变父级,它将始终有效:

$("#existingContainer").on("click", ".child", function() {
    //whatever
})

通过这种方式,事件被捕获在#existingContainer上,但回调只有在&#34; .child&#34;内被捕获时才会被执行。位于#existingContainer中的对象,无论是否在创建事件侦听器后添加了.child对象。

答案 2 :(得分:-1)

当dom manuplation发生并且它传递给$('.child').click(function())函数时,它没有在DOM中找到任何相应的元素进行操作。当您动态添加此元素时,必须在动态添加类以注册要监听的事件之后绑定/注册事件。 你可以通过

来做到这一点
 $('.parent').click(function(){
                alert('parent clicked');
                $(this).after("<span class='child' onclick='ChildelementClick()'>child</span>");
            });
function ChildelementClick(){
// do somehing
}

或者您可以使用@eisbehr

给出的示例