【问题标题】:Dynamically Adding Elements and trying to use the selectors .click event jQuery动态添加元素并尝试使用选择器 .click 事件 Jquery
【发布时间】:2012-11-03 06:56:47
【问题描述】:

我正在尝试动态添加元素并在 JQuery 中为它们设置点击侦听器。无论出于何种原因,当我单击元素“删除”按钮时,removeGroup 事件都不会触发。任何帮助都会很棒,谢谢。

$('.removeGroup').click(function(event){
    alert();
});

cartPopper.click(function(event){
    $('#selectedGroupList').find('.selected').remove();
    for(group in selectedGroups)
    {
        var group_id = selectedGroups[group];
        var name = $('.' + group_id).text();
        $('#selectedGroupList')
            .append
            (
            '<li style="font-size:20px" class="selected ' + group_id + '">'
            + '<a href="javascript: void(0);" class="">'
            + '<button class="btn btn-danger removeGroup" type="button">'
            + 'Remove'
            + '<text class="groupValue" style="display: none;">'
            + group_id + '</text></button></a>'
            + name
            + '</li>'
            );
     }
     cartPop.show();
});

【问题讨论】:

    标签: javascript jquery html javascript-events dynamic-data


    【解决方案1】:

    通俗地说,你写的代码只是将点击事件绑定到已经存在的元素上,并没有将它绑定到新创建的元素上。

    通过使用事件委托模型,您可以使其绑定到当前和未来的元素。我觉得我真的不擅长解释,所以请参考delegate()on 了解更多信息。

    替换

    $('.removeGroup').click(function(event){
        alert();
    });
    

    $(document).on('click', '.removeGroup', function(event){
        alert();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      相关资源
      最近更新 更多