我有一张表格,想要删除除第一项以外的所有标签。如何实现这个功能?
我有一张表格,想要删除除第一项以外的所有标签。如何实现这个功能?
第一行有特殊的含义吗?我要冒险猜测第一行很可能是包含列标题的行。
如果是这样,一个简单的选择是将第一行放在一个<thead>
中,将所有正文行放在一个<tbody>
中。然后你只需执行:
$('#myTable tbody tr').remove();
$('#theTable tr').slice(1).remove();
1
(第二行)开始,最后调用 .remove() 来删除这些行。querySelectorAll
方法,这将提供极快的选择速度。
querySelectorAll
在许多浏览器中都得到支持,包括 IE8
。
var rows = document.getElementById('theTable').rows;
while( rows[1] )
rows[1].parentNode.removeChild( rows[1] );
'table :first-child ~ tr'
在大多数情况下(也许是全部情况)都是有效的选择器,尽管如果有多个<tbody>
元素,则技术上可能无法满足要求。如果:gt()
或 :not(:first)
是有效的选择器就太好了。 - user113716我想我会跟上潮流并提供一些解决方案:
如果您正在使用 thead
作为第一行,请将 tr
放在 tbody
中:
$('#myTable tbody tr').remove();
thead
,那么可以通过多种方式获取其后续行。我强烈建议查看jQuery api以获得帮助。$('#myTable tr + tr').remove();
$('#myTable tr:gt(0)').remove();
$('#myTable tr:not(:first-child)').remove();
$('#myTable').find('tr').not(':first-child').remove();
$('#myTable tr:first-child').siblings().remove();
filter
将允许您调用end
并从父元素继续链接。$('#someTableSelector tr:not(:first)').remove();
- gloomy.penguin$('table :first-child ~ tr').remove();
例如: http://jsfiddle.net/TwqN3/2/ (感谢Stefan Kendall!我不知道jsfiddle。)