可能重复:
Jquery adding event listeners to dynamically added elements
jQuery位:
我将带有一些文本的输入字段附加到div:
shareVisual = '<div class="individual-share">' + '<input type="number" value="1" /> X ' + classname.val() + '@' + classcurrency.val() + ' ' + classprice.val() + ' per share ' + '<button type="button" class="remove-share">Remove</button></div>';
listOfSharesBox.append(shareVisual);
然后我尝试捕捉点击事件:
$("#list-of-shares").bind('click', '.remove-share', function() {
$(".remove-share").closest("div").find(".individual-share").remove();
});
为什么不删除DIV?
干杯。
P.S。
当我将代码更改为:
$("#list-of-shares").bind('click', '.remove-share', function() {
$(".remove-share").closest("div").remove();
});
所有动态生成的输入都会在div中被删除。
答案 0 :(得分:2)
如果您使用jquery 1.7意味着尝试这样
$(".remove-share").on('click',function() {
$(this).closest("div").remove();
});
否则使用
$(".remove-share").bind('click',function() {
$(this).closest("div").remove();
});
答案 1 :(得分:-1)
尝试使用“live”关键字来处理动态生成的控件:
$(".remove-share").live('click', function() {
$(this).closest("div").remove();
});