用jQuery删除表行最好的方法是什么?
当前回答
$('tr').click(function()
{
$(this).remove();
});
我认为你会尝试上面的代码,因为它工作,但我不知道为什么它工作了一段时间,然后整个表被删除。我还试图通过单击该行删除该行。但找不到确切的答案。
其他回答
$('tr').click(function()
{
$(this).remove();
});
我认为你会尝试上面的代码,因为它工作,但我不知道为什么它工作了一段时间,然后整个表被删除。我还试图通过单击该行删除该行。但找不到确切的答案。
另一个是empty():
$(this).closest('tr').empty();
$('#myTable tr').click(function(){
$(this).remove();
return false;
});
甚至是更好的
$("#MyTable").on("click", "#DeleteButton", function() {
$(this).closest("tr").remove();
});
如果你有这样的HTML
<tr>
<td><span class="spanUser" userid="123"></span></td>
<td><span class="spanUser" userid="123"></span></td>
</tr>
其中userid="123"是一个自定义属性,可以在构建表时动态填充,
你可以用
$(".spanUser").live("click", function () {
var span = $(this);
var userid = $(this).attr('userid');
var currentURL = window.location.protocol + '//' + window.location.host;
var url = currentURL + "/Account/DeleteUser/" + userid;
$.post(url, function (data) {
if (data) {
var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW
} else {
alert('Sorry, there is some error.');
}
});
});
在这种情况下,你不知道TR标签的类或id,但无论如何你可以删除它。
你可以使用:
$($(this).closest("tr"))
用于查找元素的父表行。
它比parent().parent()更优雅,这是我开始做的事情,很快就认识到我的错误。
——编辑 有人指出,这个问题是关于去除这一行的……
$($(this).closest("tr")).remove()
正如下面指出的,你可以简单地做:
$(this).closest('tr').remove();
类似的代码片段可用于许多操作,例如在多个元素上触发事件。