jQuery jQuery删除表格列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4544177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery delete table column
提问by eba
I have a table and cannot change markup:
我有一张表,无法更改标记:
<table>
<thead>
<tr>
<th>
blablabla
</th>
<th>
blablabla
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
efgd
</td>
<td>
efghdh
</td>
</tr>
</tbody>
</table>
Here is my function, which should delete a column. It is called on cell click:
这是我的函数,它应该删除一列。它在单元格单击时调用:
function (menuItem, menu) {
var colnum = $(this).prevAll("td").length;
$(this).closest('table').find('thead tr th:eq('+colnum+')').remove();
$(this).closest("table").find('tbody tr td:eq('+colnum+')').remove();
return;
}
But it deletes something else, not the column I wanted to delete. Where am I wrong?
但它删除了其他内容,而不是我想删除的列。我哪里错了?
回答by Ariel
A column is pretty much just cells, so you'll need to manually loop through all the rows and remove the cell by the index.
一列几乎只是单元格,因此您需要手动遍历所有行并通过索引删除单元格。
This should give you a good starting point for removing the 3rd column:
这应该为您删除第 3 列提供了一个很好的起点:
$("tr").each(function() {
$(this).filter("td:eq(2)").remove();
});
回答by user113716
This uses .delegate()
for the handler, and a more native approach using cellIndex
to get the cell index that was clicked, and cells
to pull the cell from each row.
这.delegate()
用于处理程序,以及一种更原生的方法,cellIndex
用于获取单击的单元格索引,并cells
从每一行中拉出单元格。
Example:http://jsfiddle.net/zZDKg/1/
示例:http : //jsfiddle.net/zZDKg/1/
$('table').delegate('td,th', 'click', function() {
var index = this.cellIndex;
$(this).closest('table').find('tr').each(function() {
this.removeChild(this.cells[ index ]);
});
});
回答by hackernewbie
This works fine for me:
这对我来说很好用:
$(".tableClassName tbody tr").each(function() {
$(this).find("td:eq(3)").remove();
});
回答by Amay Kulkarni
If you have the static html (consider table with 10 columns),
如果您有静态 html(考虑包含 10 列的表格),
then remove the first column along with header using below:
然后使用下面的方法删除第一列和标题:
$('#table th:nth-child(1),#table td:nth-child(1)').remove();
now the new table will have 9 columns , now you can remove any column using the number:
现在新表将有 9 列,现在您可以使用数字删除任何列:
$('#table th:nth-child(7),#table td:nth-child(7)').remove();
回答by Zahid
By Applying some class on targeted column we can remove it. For example
通过在目标列上应用一些类,我们可以将其删除。例如
<tr>
<td>ID</td>
<td>Name</td>
<td><button class="btnRemoveMember">X</button></td>
</tr>
From above example table we can remove 3rd column of table as follow.
从上面的示例表中,我们可以删除表的第 3 列,如下所示。
$(.btnRemoveMember).closest('td').remove();
回答by Eleandro
Remove the first column from each row.
从每一行中删除第一列。
$('.mytable').find("tr td:nth-child(1)").each(function(){
$(this).remove()
});