我有一个脚本,当用户点击页面上的某些div链接时,它会动态地向表中添加行。我现在正在尝试添加一个删除按钮,以便用户可以摆脱他们不想要的添加行,但我遇到了让它们工作的问题。
我用于删除表格行的代码来自here。我的代码是:
$('.addRow').click(function() {
var tr = $(
'<tr><td class="cat"></td>'
+ '<td class="sel"></td>'
+ '<td><textarea name="paragraph[' + count + ']">Click to edit (id ' + count + ')</textarea><input type="hidden" name="catText[' + count + ']" class="hiddenCat"><input type="hidden" name="selText[' + count + ']" class="hiddenSel">'
+ '</td><td><button type="button" class="removebutton">Remove row</button></td></tr>');
$('.mainTable > tbody:last').one().append(tr);
tr.find(".cat").text($(this).closest("li.category").attr("title"));
tr.find(".hiddenCat").val($(this).closest("li.category").attr("title"));
tr.find(".sel").text($(this).closest("li.select").attr("title"));
tr.find(".hiddenSel").val($(this).closest("li.select").attr("title"));
count++;
});
$('.removebutton').click(function() {
alert('Hello');
var whichtr = $(this).closest("tr");
whichtr.remove();
});
addRow函数将表行附加到选定的表。其中一个单元格中有一个带有“删除按钮”类的按钮。单击此按钮时,应该删除该行。出于测试目的,使用警报消息;但是,当我点击使用addRow动态生成的其中一个按钮时,没有任何反应。
当我静态添加带有“删除按钮”类的按钮或链接时,会显示警告消息。
为什么在通过jQuery创建按钮以阻止其工作时会出现问题?
答案 0 :(得分:2)
将.on
用于动态内容:
$(document).on('click', '.removebutton', function() {
alert('Hello');
var whichtr = $(this).closest("tr");
whichtr.remove();
});
答案 1 :(得分:2)
您需要动态创建元素的事件委派
$('.mainTable').on('click','.removebutton',function() {
alert('Hello');
var whichtr = $(this).closest("tr");
whichtr.remove();
});