我正在尝试使用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);
});
答案 0 :(得分:3)
$(this).closest("tr").remove();
, onClick='del(this);'
将正常工作。更好的是跳过丑陋的DOM0事件绑定并使用.on()
:
$(document).on('click', 'td.delete', del);
请注意,您的代码当前正在生成具有重复ID的HTML,这很糟糕。元素ID必须是唯一的。改为使用类:
$("<td class='delete'>Delete</td>").appendTo(ttr);