jQuery - 在每个函数内附加点击事件以动态添加内容

jQuery - Attach click event inside each function for dynamically added content

我遇到了一个小问题,似乎无法让它工作。

我有这个作为标记。

    <div id="label-group" class="label-group">
        <!-- Label Item -->
        <div id="label-1" class="label-item">
            <div class="label-line">
                <a href="#" class="btn btn-small btn-simple btn-assign-schedule">Assign Schedule to Label</a>
            </div>
            <div class="label-head clearfix"> 
                <div class="label-title">  
                    UK Call Menus 
                </div> 
                <div class="label-tools"> 
                    <a href="#" class="delete" title="Delete Label"></a>
                    <a href="#" class="moveup" title="Move Up"></a>
                    <a href="#" class="movedown" title="Move Down"></a>
                    <a href="#"  class="toggle" title="Open &amp; Close"></a> 
                </div>
            </div>
       </div>
   </div>

而这个 jQuery 使用所有标签工具链接并在点击时添加某些功能。

$(".label-group .label-tools a").each(function(){  
    $(this).on('click',function(e) {
        e.preventDefault(); 
        var li = $(this).closest(".label-item");

        if ($(this).hasClass('movedown')) {
                    li.css('opacity','0.5');
                    li.next().css('opacity','0.5');  
                    li.insertAfter(li.next()).animate({opacity:"1"},200); 
                    li.prev().animate({opacity:"1"},300);
        } else if ($(this).hasClass('moveup')) {
                    li.css('opacity','0.5');
                    li.prev().css('opacity','0.5');
                    li.insertBefore(li.prev()).animate({opacity:"1"},200);  
                    li.next().animate({opacity:"1"},300);
        } else if ($(this).hasClass('toggle')) {
                var liContent = $(this).closest(".label-head").siblings('.label-content');
                    liContent.toggle(0,function(){
                        li.toggleClass('label-open');  
                    });   
        } else if ($(this).hasClass('delete')) {
                    li.remove();   
        }
    })
})

当我将另一个 .label-item 动态添加到 .label-group 时,标签工具链接根本不起作用。

目前您使用的是 "direct" 绑定,它只会附加到您的代码进行事件绑定调用时页面上存在的元素。

在动态生成元素或操作选择器(如删除和添加 类)时,您需要使用 Event Delegation using .on() 委托事件方法。

$(document).on('event','selector',callback_function)

例子

$(staticParentContainer).on('click',".label-group .label-tools a",function(e) {
    //Your existing code
});

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.