选择奇数和偶数元素

时间:2015-09-01 04:36:55

标签: jquery html css

我想将classpath 'com.android.tools.build:gradle:1.3.0' odd even元素设置为与我的表格不同。

这是我的代码:

jsFiddle



tr

/*
Create a one-liner code to add the class ‘odd’ to an odd number row and the class ‘even’ to an even number row
Hint: Use the nth-child selector and the end() function
*/

table,
tr,
td {
  border-collapse: collapse;
  border: 1px solid #000;
}
table {
  width: 100%;
}
tr.odd {
  background: rgba(0, 255, 0, 0.1);
}
tr.even {
  background: rgba(0, 0, 0, 0.1);
}




提示:使用nth-child选择器和end()函数

4 个答案:

答案 0 :(得分:3)

如果你有jQuery,可以使用:odd:even选择器

UIWindowLevelNormal

Demo



$('tr:odd').addClass('odd');
$('tr:even').addClass('even');

$('tr:odd').addClass('odd');
$('tr:even').addClass('even');

table,
tr,
td {
  border-collapse: collapse;
  border: 1px solid #000;
}
table {
  width: 100%;
}
tr.odd {
  background: rgba(0, 255, 0, 0.1);
}
tr.even {
  background: rgba(0, 0, 0, 0.1);
}




仅使用CSS

您还可以使用CSS <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <table> <tr> <td>odd</td> <td>odd</td> </tr> <tr> <td>even</td> <td>even</td> </tr> <tr> <td>odd</td> <td>odd</td> </tr> <tr> <td>even</td> <td>even</td> </tr> <tr> <td>odd</td> <td>odd</td> </tr> </table>选择器选择奇数和偶数元素。

&#13;
&#13;
nth-child
&#13;
table,
tr,
td {
  border-collapse: collapse;
  border: 1px solid #000;
}
table {
  width: 100%;
}
tr:nth-child(2n) {
  background: rgba(0, 255, 0, 0.1);
}
tr:nth-child(2n + 1) {
  background: rgba(0, 0, 0, 0.1);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试使用css :nth-of-type()伪类选择器集oddeven

table,
tr,
td {
  border-collapse: collapse;
  border: 1px solid #000;
}
table {
  width: 100%;
}
tr:nth-of-type(odd) {
  background: rgba(0, 255, 0, 0.1);
}
tr:nth-of-type(even) {
  background: rgba(0, 0, 0, 0.1);
}
<table>
  <tr>
    <td>odd</td>
    <td>odd</td>
  </tr>
  <tr>
    <td>even</td>
    <td>even</td>
  </tr>
  <tr>
    <td>odd</td>
    <td>odd</td>
  </tr>
  <tr>
    <td>even</td>
    <td>even</td>
  </tr>
  <tr>
    <td>odd</td>
    <td>odd</td>
  </tr>
</table>

答案 2 :(得分:1)

尝试CSS奇数/偶数选择器。

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

答案 3 :(得分:0)

尝试使用伪类选择器添加样式:nth-​​of-type,偶数和奇数。

table,
tr,
td {
  border-collapse: collapse;
  border: 1px solid #000;
}
table {
  width: 100%;
}
tr:nth-of-type(odd) {
  background: rgba(0, 255, 0, 0.1);
}
tr:nth-of-type(even) {
  background: rgba(0, 0, 0, 0.1);
}
<table>
  <tr>
    <td>odd</td>
    <td>odd</td>
  </tr>
  <tr>
    <td>even</td>
    <td>even</td>
  </tr>
  <tr>
    <td>odd</td>
    <td>odd</td>
  </tr>
  <tr>
    <td>even</td>
    <td>even</td>
  </tr>
  <tr>
    <td>odd</td>
    <td>odd</td>
  </tr>
</table>