用jQuery删除表行最好的方法是什么?
当前回答
另一个是empty():
$(this).closest('tr').empty();
其他回答
如果要删除的行可能发生变化,可以使用此方法。只需将您希望删除的行#传递给该函数。
function removeMyRow(docRowCount){
$('table tr').eq(docRowCount).remove();
}
假设您在表中的数据单元格中有一个按钮/链接,像这样的东西可以做到这一点……
$(".delete").live('click', function(event) {
$(this).parent().parent().remove();
});
这将删除所单击的按钮/链接的父级的父级。您需要使用parent(),因为它是一个jQuery对象,而不是一个普通的DOM对象,并且您需要使用parent()两次,因为按钮位于数据单元格中,而数据单元格位于行....中这就是你想要移除的东西。$(this)是被点击的按钮,所以简单地这样做只会删除按钮:
$(this).remove();
这将删除数据单元格:
$(this).parent().remove();
如果你想简单地单击行上的任何地方来删除它,这样就可以了。你可以很容易地修改它来提示用户或只在双击时工作:
$(".delete").live('click', function(event) {
$(this).parent().remove();
});
简单. .试试这个
$("table td img.delete").click(function () {
$(this).parent().parent().parent().fadeTo(400, 0, function () {
$(this).remove();
});
return false;
});
如果你有这样的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,但无论如何你可以删除它。
从表中删除行最简单的方法:
使用表的唯一ID删除行。 根据该行的顺序/索引进行删除。例如:删除第三行或第五行。
例如:
<table id='myTable' border='1'>
<tr id='tr1'><td>Row1</td></tr>
<tr id='tr2'><td>Row2</td></tr>
<tr id='tr3'><td>Row3</td></tr>
<tr id='tr4'><td>Row4</td></tr>
<tr id='tr5'><td>Row5</td></tr>
</table>
//======REMOVE TABLE ROW=========
//1. remove spesific row using its ID
$('#tr1').remove();
//2. remove spesific row using its order or index.
//row index started from 0-n. Row1 index is 0, Row2 index is 1 and so on.
$('#myTable').find('tr:eq(2)').remove();//removing Row3