动态添加元素并尝试使用选择器.click事件Jquery [英] Dynamically Adding Elements and trying to use the selectors .click event Jquery

查看:118
本文介绍了动态添加元素并尝试使用选择器.click事件Jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图动态添加元素,并在JQuery中为它们添加点击侦听器。无论出于何种原因,当我点击一个元素的删除按钮时,removeGroup事件不会被启动。
$ b

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


推荐答案

将click事件绑定到已存在的元素,并且不会将其绑定到新创建的元素。

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.

通过使用事件委托模型,可以将它绑定到当前和将来的元素。我想我解释得很糟糕,所以请参阅委托() on 获取更多信息。

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.

替换

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

使用

With

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

这篇关于动态添加元素并尝试使用选择器.click事件Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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