用jQuery删除表行最好的方法是什么?
当前回答
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');
其他回答
如果你有这样的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,但无论如何你可以删除它。
如果您正在使用引导表
将此代码片段添加到bootstrap_table.js中
BootstrapTable.prototype.removeRow = function (params) {
if (!params.hasOwnProperty('index')) {
return;
}
var len = this.options.data.length;
if ((params.index > len) || (params.index < 0)){
return;
}
this.options.data.splice(params.index, 1);
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initBody(true);
};
然后在你的var allowedMethods = [
添加“removeRow”
最后你可以使用$("#your-table").bootstrapTable('removeRow',{index:1});
本文致谢
function removeRow(row) {
$(row).remove();
}
<tr onmousedown="removeRow(this)"><td>Foo</td></tr>
也许像这样的东西也能起作用?我还没有尝试过用“this”做什么,所以我不知道它是否有效。
从表中删除行最简单的方法:
使用表的唯一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
你是对的:
$('#myTableRow').remove();
如果你的行有一个id,这可以很好地工作,比如:
<tr id="myTableRow"><td>blah</td></tr>
如果你没有id,你可以使用jQuery的任何一个选择器。