-1

我有一张这样的桌子:

<table>
   <tr>
      <th>h1</th>
      <th>h2</th>
      <th>h3</th>
  </tr>

  <tr>
      some content here
  </tr>

  <tr>
      <td>1</td> <td>2</td> <td>3</td>
  </tr>
  <tr>
      inside this row, I have a table which contains 2 rows
  </tr>


   <tr>
      <td>1</td> <td>2</td> <td>3</td>
  </tr>
  <tr>
      inside this row, I have a table which contains 2 rows
  </tr>

   <tr>
      <td>1</td> <td>2</td> <td>3</td>
  </tr>
  <tr>
      inside this row, I have a table which contains 2 rows
  </tr>
  //it repeats like this


</table>

我想从第 3 行开始使用 jquery 为每 3 行应用替代颜色,即,我希望以下代码部分具有替代颜色。我该怎么做?谢谢

      <tr>
         <td>1</td> <td>2</td> <td>3</td>
      </tr>
      <tr>
          inside this row, I have a table which contains 2 rows
      </tr>

基本上,我不想选择标题行和标题行之后的第一行。之后,我想每次选择 3 行,并给它另一种颜色。3 行将是如上所示的行。

4

4 回答 4

2

使用第 n 个子选择器

$("table tr:nth-child(3n)")
于 2013-02-11T21:30:36.927 回答
1
$('table tr:nth-child(3n) td').css('background-color', 'red');
$('table tr:nth-child(3n+1) td').css('background-color', 'blue');
$('table tr:nth-child(3n+2) td').css('background-color', 'green');
于 2013-02-11T21:34:53.793 回答
0

你可以使用纯css3

table tr:nth-child(3n+3) { background:red; }

或者也通过 jquery,比如 kmd97 答案

$("table tr:nth-child(3n+3)").css("background","red");

3n 表示每 3 个元素,+3 表示从第 3 个元素开始。

你可以试试这个在线 CSS 测试器

于 2013-02-11T21:53:00.637 回答
0
var totalOfRows = $('table').find('tr').length;

var rows = $('table').find('tr');

for(var i=0; i<totalOfRows;i++){
 $(rows[i]).attr('bgcolor','red'); //logical here
}

for example, yo can write .css('background-color', 'blue'); .css('background-color', 'pink'); etc
于 2013-02-11T21:34:50.253 回答