Jquery显示/隐藏表行

我希望能够使用jquery显示/隐藏表中的行。 理想情况下,我希望桌子上方有按钮来对表格进行排序。

即[显示ID为黑色的行] [显示ID为白色的行] [显示所有行]

我已经搜遍了所有但无法找到解决方案。 任何人都知道如何用jquery做到这一点,并使其跨浏览器兼容?

谢谢(以下代码)

将您的黑白ID更改为类(重复ID无效),添加具有正确ID的2个按钮,并执行以下操作:

 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(); }); 

    
bla bla bla
Header Text Header Text Header Text Header Text Header Text Header Text
Some Text Some Text Some Text Some Text Some Text Some Text
Some Text Some Text Some Text Some Text Some Text Some Text
... ... ...
bla bla bla

它使用filter() [docs]方法过滤blackwhite类的行(取决于按钮)。

然后它使用not() [docs]方法执行相反的filter,排除先前找到的blackwhite行。


编辑:您也可以将选择器传递给.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(); }); 

过滤function对我来说根本不起作用; 也许更新版本的jquery不能像上面代码中使用的那样执行。 而不管; 我用了:

  var black = $('.black'); var white = $('.white'); 

选择器将找到归类为黑色或白色的每个元素。 按钮function保持如上所述:

  $('#showBlackButton').click(function() { black.show(); white.hide(); }); $('#showWhiteButton').click(function() { white.show(); black.hide(); }); 

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

 Show only black
Show only white
Show all of them
bla bla bla
Header Text Header Text Header Text Header Text Header Text Header Text
Some Text Some Text Some Text Some Text Some Text Some Text
Some Text Some Text Some Text Some Text Some Text Some Text