根据日期添加交替表格行颜色?

时间:2016-06-19 20:20:52

标签: html

我在html中有一个表,每行的第一列包含一个日期。我想根据日期给出某种分离。所以今天日期的所有行都是深灰色,昨天的行是浅灰色的,然后两天前会再次变成灰色等等。

有一种简单的方法吗?

由于

1 个答案:

答案 0 :(得分: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
				if (value == tableDate) {
        	if (shouldColor == true) {
        		$('#MyTable tbody tr:nth-child(' + (i + 1) + ')').addClass("alternate");
            } 
         
        } else {
        		if (shouldColor == false) {
            	shouldColor = true
              $('#MyTable tbody tr:nth-child(' + (i + 1) + ')').addClass("alternate");
            } else {
            	shouldColor = false
            }	
        }
    		
tableDate = value
});
#MyTable {
		width:100%; 
		border-collapse:collapse; 
	}
#MyTable td { 
		padding:7px; border:blue 1px solid;
	}

#MyTable tr {
		background: light-grey;
	}
  
  

#MyTable .alternate { 
		background: red;
	}
<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>