2013-06-03 35 views
0

我試圖用jQuery刪除一個錶行。我使用了所有我能找到的方法,但都沒有成功。 我在每行的末尾都有一個刪除,當我點擊它時,我觸發一個函數,它應該刪除它所在的行。但它不會工作。正在刪除當前行jQuery

在評論是我的嘗試失敗。 是否存在像第一個那樣的僞造,但對於當前項目(類似這樣的)?

function del(){ 

//$(this).parent().parent().remove(); 
//$(this).closest("tr").remove(); 
//$('table tr:last').remove(); this one worked but it deletes the last and I want the current one to be deleted 

} 

這裏是生成表的代碼:

$.getJSON("nutritional_value.php?value=" + encodeURI(value), function (data) { 
var ttr = $("<tr class='rou' />"); 
$.each(data, function(k, v){ 
var store_1 = v * (parseFloat(uneseno, 10)/100); 
var xstore_1 = store_1.toFixed(2); 

$("<td class='teedee'></td>").text(k=='name' ? v : xstore_1).appendTo(ttr); 



}); 
$("<td id='delete' onClick='del();'>Delete</td>").appendTo(ttr); 
$("#tejbl").append(ttr); 
}); 

回答

3

$(this).closest("tr").remove();如果你改變使用onClick='del(this);'的HTML將工作得很好。更妙的是跳過醜陋DOM0事件綁定,並使用.on()

$(document).on('click', 'td.delete', del); 

請注意,你的代碼目前正在與重複的ID生成HTML,這是壞的,壞的壞。元素ID必須是唯一的。改用類:

$("<td class='delete'>Delete</td>").appendTo(ttr); 
+0

謝謝!完美的作品。並感謝您的額外提示:) – Filkatron