jQuery显示/隐藏表行 [英] Jquery show/hide table rows
问题描述
我希望能够使用jquery显示/隐藏表中的行.理想情况下,我想在表格上方设置按钮以对表格进行排序.
I want to be able to show/hide the rows in a table using jquery. Ideally I want to have buttons above the table to sort the table with.
即[显示ID:黑色的行] [显示ID:白色的行] [显示所有行]
i.e [Show rows with id:black] [Show rows with id:white] [Show all rows]
我已经搜索了所有内容,但找不到解决方案.有谁知道我如何使用jquery做到这一点并使它跨浏览器兼容?
I have searched all over but cannot find a solution. Anyone know how i can do this with jquery and make it cross browser compatible?
谢谢(下面的代码)
<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的按钮,然后执行以下操作:
Change your black and white IDs to classes instead (duplicate IDs are invalid), add 2 buttons with the proper IDs, and do this:
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()
[docs] 方法来过滤具有black
或white
类的行(取决于按钮).
It uses the filter()
[docs] method to filter the rows with the black
or white
class (depending on the button).
然后,它使用> not()
[docs] 方法执行相反的过滤器,但不包括先前找到的black
或white
行.
Then it uses the not()
[docs] method to do the opposite filter, excluding the black
or white
rows that were previously found.
编辑:您也可以将选择器传递给.not()
而不是以前找到的集合.这样可能会更好:
You could also pass a selector to .not()
instead of the previously found set. It may perform better that way:
rows.not( `.black` ).hide();
// ...
rows.not( `.white` ).hide();
...或更妙的是,只需从一开始就保留两者的缓存集:
...or better yet, just keep a cached set of both right from the start:
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显示/隐藏表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!