1

我正在使用 dataTable,我正在动态地将数据传递给表,我想更改前 4 行的行的背景颜色,并分别为下一组 4 行重复这些颜色,依此类推。

我尝试使用 :nth-child css 选择器,但我可以选择奇数行/偶数行或指定我想在下面制作的行号

$("tr:nth-child(1)").css("background-color", "orange");
$("tr:nth-child(2)").css("background-color", "green");
$("tr:nth-child(3)").css("background-color", "blue");
$("tr:nth-child(4)").css("background-color", "yellow");
$("tr:nth-child(5)").css("background-color", "orange");
$("tr:nth-child(6)").css("background-color", "green");
$("tr:nth-child(7)").css("background-color", "blue");
$("tr:nth-child(8)").css("background-color", "yellow");
4

1 回答 1

0

您已经使用了正确的选择器,:nth-child但是您需要使用函数符号来根据当前行索引计算颜色,n

$("tr:nth-child(4n+1)").css("background-color", "orange");
$("tr:nth-child(4n+2)").css("background-color", "green");
$("tr:nth-child(4n+3)").css("background-color", "blue");
$("tr:nth-child(4n+4)").css("background-color", "yellow");
table { width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr><td>1</td></tr>
  <tr><td>2</td></tr>
  <tr><td>3</td></tr>
  <tr><td>4</td></tr>
  <tr><td>5</td></tr>
  <tr><td>6</td></tr>
  <tr><td>7</td></tr>
  <tr><td>8</td></tr>
</table>

话虽如此,您不应该使用 Javascript 来执行此操作。直接使用 CSS:

table { width: 100%; }

tr:nth-child(4n+1) { background-color: orange; }
tr:nth-child(4n+2) { background-color: green; }
tr:nth-child(4n+3) { background-color: blue; }
tr:nth-child(4n+4) { background-color: yellow; }
<table>
  <tr><td>1</td></tr>
  <tr><td>2</td></tr>
  <tr><td>3</td></tr>
  <tr><td>4</td></tr>
  <tr><td>5</td></tr>
  <tr><td>6</td></tr>
  <tr><td>7</td></tr>
  <tr><td>8</td></tr>
</table>

于 2019-09-09T18:04:55.997 回答