【问题标题】:alternate table rows with different colors [duplicate]具有不同颜色的交替表行[重复]
【发布时间】:2021-06-22 16:40:06
【问题描述】:

使用以下代码,我生成了一个表格,其中填充了从 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; }

我该怎么办?

【问题讨论】:

  • 它不起作用”不是一个有用的问题陈述。编辑您的问题,以包含具体说明如何您知道它不起作用(预期与实际行为)。如果没有看到此代码作为 Minimal, Reproducible Example 运行的 HTML,也几乎不可能明确说明为什么这不起作用。
  • 使用该 css 代码,行不会交替并且没有任何变化
  • 您的追加过程不正确。当您将行追加到表中,然后将单元格追加到表中时,单元格不会插入行中。您不能像在代码编辑器中编写 html 一样插入结束标记。 DOM 只理解完整的元素

标签: javascript html jquery css html-table


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多