我正在尝试动态添加元素,并在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();
});
答案 0 :(得分:5)
在外行语中,您编写的代码仅将click事件绑定到已存在的元素,并且不会将其绑定到新创建的元素。
通过使用事件委派模型,您可以将其绑定到当前和未来元素。我认为我的解释非常糟糕,请参阅delegate()和on以获取更多信息。
替换
$('.removeGroup').click(function(event){
alert();
});
使用
$(document).on('click', '.removeGroup', function(event){
alert();
});