You ca n委託click
處理程序(可能是更好的解決方案),或者只是在創建行時將其分配。下面的例子(使用DOM元素創建,而不是HTML標記,因爲這是一個更好的做法)。
// delegate the function once in your DOM.ready
$('#giants_table tr').on('click', 'input[type="button"][value="Remove Row"]', function (e) {
$(this).parents('tr').remove(); // this will point to the input
});
// or assign it when you create the row
function add_row(){
var input = $('<input />'), //create new DOM elements
row = $('<tr />'),
cell = $('<td />'),
rowCount = $('#giants_table tr').length;
$('#giants_table tr:last').before(tr.append(td.append(input.clone().attr({
"id": "giants_" + rowCount,
"name": "giants_" + rowCount,
"type": "text"
})).append(input.clone().attr({
"id": "removeRow" + rowCount,
"type": "button",
"value": "Remove Row"
}).click(function (e) {
$(this).parents('tr').remove(); // this now points to the input
}))));
}
刪除包裹'''','this'不是一個字符串,它是一個指針。 – Johan
你有jQuery - 使用它來註冊你的事件處理程序,而不是將它們內聯,並且答案應該變得明顯!更好的是,在整個表上使用一個委託事件處理程序來處理'remove_row'按鈕。 – Alnitak
@Alnitak你怎麼知道他沒有引用jQuery事件處理函數? – Johan