用jQuery删除表行最好的方法是什么?
当前回答
如果要删除的行可能发生变化,可以使用此方法。只需将您希望删除的行#传递给该函数。
function removeMyRow(docRowCount){
$('table tr').eq(docRowCount).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,但无论如何你可以删除它。
以下是可以接受的:
$('#myTableRow').remove();
从表中删除行最简单的方法:
使用表的唯一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
Id现在不是一个好的选择器。您可以在行上定义一些属性。你可以用它们作为选择器。
<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>
你可以使用func来选择行,就像这样(ES6):
const rowRemover = (category,type)=>{
$(`tr[category=${category}][type=${type}]`).remove();
}
rowRemover('petshop','fish');
function removeRow(row) {
$(row).remove();
}
<tr onmousedown="removeRow(this)"><td>Foo</td></tr>
也许像这样的东西也能起作用?我还没有尝试过用“this”做什么,所以我不知道它是否有效。