【问题标题】:Coloring every second row with rowspan使用 rowspan 每隔一行着色一次
【发布时间】:2017-02-09 21:52:48
【问题描述】:

我想每隔一行给表格上色。虽然每个常规表格都可以使用以下颜色进行着色:

$('tr:odd').css( "background-color", "orange" );

在我的情况下,有几个rowspan,这让任务变得更加困难。

这是我想要的输出:

使用上面的这段代码不会得到想要的结果:

Here is a fiddle.

$('tr:odd').css("background-color", "orange");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td>Col 2</td>
    <td rowspan="2">Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td rowspan="2">Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
</table>

【问题讨论】:

标签: javascript jquery css html-table


【解决方案1】:

做这样的事情:

$("table tr").filter(function() { 
  return $(this).children().length == 3;
}).filter(':odd').addClass('alt');

$("tr.alt td[rowspan]").each(function() {
  $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
});
.alt { background-color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td>Col 2</td>
    <td rowspan="2">Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td rowspan="2">Col 1</td>
    <td rowspan="2">Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <td>Col 1</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
</table>

【讨论】:

  • 无需迭代同一行中的所有rowspan td
猜你喜欢
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
相关资源
最近更新 更多