Dynamically Adding Elements and trying to use the selectors .click event Jquery

半世苍凉 提交于 2019-12-18 09:45:24

问题


I'm trying to dynamically add elements and have click listeners for them in JQuery. For whatever reason the removeGroup event does not get set off when I click on an elements 'remove' button. Any help would be great, thanks.

$('.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();
});

回答1:


In laymans terms, the code which you have written only binds a click event to elements that already exist and doesnt bind it to newly created elements.

By using the event delegation model, you can make it bind to current and future elements. I think I'm really bad at explaining so please refer to delegate() and on for more information.

Replace

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

With

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


来源:https://stackoverflow.com/questions/13384588/dynamically-adding-elements-and-trying-to-use-the-selectors-click-event-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!