jQuery选择隐形tr偶数块

时间:2013-06-11 05:24:26

标签: javascript jquery

我有一张大桌子,其中一些<tr>元素被隐藏display: none。我试图用jquery选择所有visible块,并为它们添加一个css样式。我试过这样的事情:

$('#table tr').css('background-color', 'rgb(255, 255, 255)');  //give all rows white background
$('#table tr:visible').filter(':even').css('background-color', 'rgb(242, 242, 242)'); //select all even VISIBLE blocks, and add gray color to them

出于某种原因,我当前的代码甚至是所有偶数块,甚至是那些不可见的块。我该如何改进我的代码?那个错误呢?

编辑: 我也试过这样的事情:

 $('#table tr:visible').filter(':even').css('background-color', 'rgb(242, 242, 242)');
  $('#table tr:visible').filter(':odd').css('background-color', 'rgb(255, 255, 255)');

再一次,它甚至为不可见的块着色..

2 个答案:

答案 0 :(得分:0)

试试这个,

// white background for odd rows
$('#table tr:odd').css('background-color', 'rgb(255, 255, 255)'); 
//select all even VISIBLE blocks, and add gray color to them
$('#table tr:visible:even').css('background-color', 'rgb(242, 242, 242)'); 

//or if you have hidden class for hidden rows then you can use like,
$('#table tr:even').not('.hiddenclass')
                   .css('background-color', 'rgb(242, 242, 242)'); 

答案 1 :(得分:0)

请注意,根据jquery docs on :visible,任何具有宽度和高度的元素即使具有可见性,也会被视为可见:隐藏或不透明:0设置。

你应该在可见的tr元素上设置一个类(如果你还没有),并根据该类选择,例如“#table .visible:even”