我希望能够使用jquery显示/隐藏表中的行。理想情况下,我想在表格上方设置按钮以对表格进行排序。
即[显示ID为:黑色的行] [显示ID为:白色的行] [显示所有行]
我到处搜索,但找不到解决方案。任何人都知道我如何用jquery做到这一点并使它跨浏览器兼容?
谢谢(下面的代码)
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
<tr id="black">
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
</tr>
</thead>
<tbody>
<tr id="white">
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
</tr>
<tr id="black">
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
</tr>
</tbody>
最佳答案
将您的黑白ID改为类(重复的ID无效),添加2个具有正确ID的按钮,然后执行以下操作:
var rows = $('table.someclass tr');
$('#showBlackButton').click(function() {
var black = rows.filter('.black').show();
rows.not( black ).hide();
});
$('#showWhiteButton').click(function() {
var white = rows.filter('.white').show();
rows.not( white ).hide();
});
$('#showAll').click(function() {
rows.show();
});
<button id="showBlackButton">show black</button>
<button id="showWhiteButton">show white</button>
<button id="showAll">show all</button>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
<tr class="black">
...
</tr>
</thead>
<tbody>
<tr class="white">
...
</tr>
<tr class="black">
...
</tr>
</tbody>
</table>
它使用
filter()
方法来过滤带有black
或white
类(取决于按钮)的行。然后,它使用
not()
方法执行相反的筛选,不包括先前找到的black
或white
行。编辑:您也可以将选择器传递给
.not()
,而不是先前找到的集合。这样可能会更好:rows.not( `.black` ).hide();
// ...
rows.not( `.white` ).hide();
...或者更好的是,从一开始就保留两者的缓存集:
var rows = $('table.someclass tr');
var black = rows.filter('.black');
var white = rows.filter('.white');
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
关于jquery - jQuery显示/隐藏表行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6686377/