具有不同颜色的交替表格行

时间:2021-03-25 20:18:32

标签: javascript html jquery css html-table

使用以下代码生成一个表格,其中包含从 json 文件中获取的数据:

$(function() {
      $.getJSON("Api/TabellaTempoMedio.php", function(data) {
        $.each(data, function(index, row) {
          $("#result").append("<tr>");

          $.each(row, function(index2, column) {
            $("#result").append("<td>" + column + "</td>");
          });

          $("#result").append("</tr>");
        });
      });
    });

这是HTML代码:

<table>
    <thead>
        <tr>
          <th>Field1</th>
          <th>Field2</th>         
        </tr>
      </thead>

      <tbody id="result">
      </tbody>
</table>

但我不能用不同的颜色交替表格的行。 我在 CSS 上试过这个,但它不起作用:

tr:nth-child(odd)  { background-color: grey; }

我该怎么办?

1 个答案:

答案 0 :(得分:-1)

.table-1{
  background: red;
}

.table-1 tr{
  background: blue;
}

.table-1 tr:nth-child(2n + 1){
  background: yellow;
}
<table class="table-1">
    <tr>
        <td>Data...</td>
    </tr>
    <tr>
        <td>Data...</td>
    </tr>
    <tr>
        <td>Data...</td>
    </tr>
    <tr>
        <td>Data...</td>
    </tr>
</table>