2016-06-19 45 views
0

我在html中有一個表格,每行的第一列包含一個日期。我想根據日期進行某種分離。所以今天的所有行都是暗灰色的,昨天的行會是淺灰色的,然後兩天前會是灰色的,等等。根據日期添加交替的表格行顏色?

有沒有簡單的方法來做到這一點?

感謝

回答

1

要有交替行不同的顏色(與具有相同日期的多個行),你必須使用jQuery通過所有表中的行迭代,以檢查它是否應該顏色行或不。

下面是一個例子的jQuery,HTML和CSS。

// iterate over each row 
 
var tableDate = $("#MyTable tbody").parents('tr:first').find('td:first').text(); 
 
var shouldColor = true 
 
$("#MyTable tbody tr").each(function(i) { 
 
    // find the first td in the row 
 
    var value = $(this).find("td:first").text(); 
 
    // display the value in console 
 
\t \t \t \t if (value == tableDate) { 
 
     \t if (shouldColor == true) { 
 
     \t \t $('#MyTable tbody tr:nth-child(' + (i + 1) + ')').addClass("alternate"); 
 
      } 
 
      
 
     } else { 
 
     \t \t if (shouldColor == false) { 
 
      \t shouldColor = true 
 
       $('#MyTable tbody tr:nth-child(' + (i + 1) + ')').addClass("alternate"); 
 
      } else { 
 
      \t shouldColor = false 
 
      } \t 
 
     } 
 
    \t \t 
 
tableDate = value 
 
});
#MyTable { 
 
\t \t width:100%; 
 
\t \t border-collapse:collapse; 
 
\t } 
 
#MyTable td { 
 
\t \t padding:7px; border:blue 1px solid; 
 
\t } 
 

 
#MyTable tr { 
 
\t \t background: light-grey; 
 
\t } 
 
    
 
    
 

 
#MyTable .alternate { 
 
\t \t background: red; 
 
\t }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 
<table id="MyTable" > 
 
    <tbody> 
 
    <tr> 
 
    <td>4/4/2016</td>  <td>Running</td> 
 
    </tr> 
 
    <tr> 
 
    <td>4/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>5/4/2016</td>  <td>Running</td> 
 
    </tr> 
 
    <tr> 
 
    <td>6/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>6/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>6/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>6/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>7/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>7/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>8/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>9/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>10/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>11/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>11/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>12/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>12/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>12/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>13/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>13/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    <tr> 
 
    <td>13/4/2016</td>  <td>Swimming</td> 
 
    </tr> 
 
    
 
</tbody> 
 
</table>

+0

是的,我大概應該解釋說,也許每個日期多行所以有可能是今天3行,5明天再1 2天前。 我認爲jQuery將不得不用某種方式?感謝您的回覆 –

+0

查看修改後的答案:) –

+0

哇,真是太棒了,非常感謝你! –