我在 html 中创建了一个表格,然后将其填充到下表中(在我的 document.ready 函数中调用了 drawTable)。对于每一行,最后都有一个按钮,用于添加具有相同 id 的另一行,直接插入下方。table(#fieldTable) td 元素的单击处理程序适用于最初插入的所有按钮。当他们单击“+”按钮时,它会在末尾添加带有“-”按钮的行。现在这在屏幕上显示得很好,但是单击时,表 td 单击处理程序不会被触发,但文档会。
我希望能够捕获单击删除(“-”)按钮,并从表中删除该行。
function drawTable() {
//fill a table I created in html, (not important for this question)
//it now looks like this
| ID | NAME | VALUE | ACTION |
| 1 | Test | <input> | + |
| 2 | Test2 | <input> | + |
//where the action column is a button (+ indicates create a new row)
//so when they click the grid this gets called
$('#fieldTable td').click(function() {
var row = $(this).parent().parent().children().index($(this).parent());
var col = $(this).parent().children().index($(this));
if(col != 3)
{
return;
}
var text = $(this).parents('tr').find('td:last').text();
var etiId = $(this).parents('tr').find('td:first').text();
console.log(text);
if(text == "+")
{
var $tr = $(this).closest('tr');
var $clone = $tr.clone();
$clone.find(':text').val('');
$clone.find('td:nth-child(2)').text('');
$clone.find('td:nth-child(4)').find('button').text('-');
$tr.after($clone);
}
//so now the grid would look like this
| ID | NAME | VALUE | ACTION |
| 1 | Test | <input> | + |
| 1 | | <input> | - |
| 2 | Test2 | <input> | + |
//the issue is, if I click the "-" button, this handler does not get called
// the document.on('click'...) does, but I am not sure how to determine the
// row/column of the button click and then remove that row
else if(text == "-")
{
console.log("remove");
$(this).parent().parent().remove();
}
});
$(document).on('click', '.btnAddRemove', function() {
console.log("document cliked");
});
}