0
我在html中創建一個表,然後將其填充到下表(drawTable在我的document.ready函數中調用)。對於每一行,末尾有一個按鈕,用於添加具有相同ID的另一行,並直接插入下方。表(#fieldTable)td元素的clicked處理程序對最初插入的所有按鈕都正常工作。當他們點擊「+」按鈕時,它會在最後添加帶有「 - 」按鈕的行。現在這個在屏幕上顯示得很好,但是當點擊時,表單點擊處理程序不會被觸發,但是文檔卻可以。在jquery中動態創建按鈕的點擊處理程序
我希望能夠捕獲點擊刪除(「 - 」)按鈕,並從表中刪除該行。
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");
});
}
所以它仍然會引用相同的$(this)對象和所有東西? – Andrew
@Andrew是的,它會引用'td'元素 –