2017-07-23 40 views
0

如果日期大於,我在表td上設置css類的腳本有問題。腳本只在今天工作。如果td中的日期低於星期且大於星期,則其餘的if應該設置類。Javascript set class by date大於

$('td:nth-child(7) ').each(function() { 

     var today = new Date(); 
     var week = new Date(); 
     var dd = today.getDate(); 
     var ddd = today.getDate()+7; 
     var mm = today.getMonth()+1; 
     var yyyy = today.getFullYear(); 

     if(dd<10) { 
      dd = '0'+dd 
     } 

     if(mm<10) { 
      mm = '0'+mm 
     } 

     today = dd + '/' + mm + '/' + yyyy; 

     if ($(this).text() == today) { 
      $(this).closest("td").addClass("red"); 
     } 
     if ($(this).text() < today + 7 && $(this).text() != today) { 
      $(this).closest("td").addClass("yellow"); 
     } 
     if ($(this).text() > today + 7) { 
      $(this).closest("td").addClass("green"); 
     } 
    }); 
+0

你可以添加一些HTML代碼? –

+0

嘗試使用'today'文本(可能是'todayText')的其他變量,現在登錄'today + 7',看看它是否是你想要的日期或字符串 – yonatanmn

回答

0

嘗試像

var displayedDate = new Date($(this).text()); 
    var today = new Date(); 
    if (displayedDate > today.setDate(today.getDate() + 7) { 
     // here displayed date is posterior to today + 7 days 

    } 
0

你比較字符串,沒有日期。您應該將單元格中的日期轉換爲Date object

而當比較日期的相等時,您應該使用valueOf()以避免參考比較。

這裏有一個工作示例:

$('td').each(function() { 
 

 
    var today = new Date(); 
 
    today.setHours(0,0,0,0); 
 
    
 
    var nextWeek = new Date(today); 
 
    nextWeek.setDate(nextWeek.getDate() + 7); 
 
    
 
    var cellDateParts = $(this).text().split("/"); 
 
    var cellDate = new Date(cellDateParts[2], parseInt(cellDateParts[1]) - 1, cellDateParts[0]); 
 
    
 
    if (cellDate.valueOf() === today.valueOf()) { 
 
    $(this).closest("td").addClass("red"); 
 
    } else if (cellDate < nextWeek) { 
 
    $(this).closest("td").addClass("yellow"); 
 
    } else if (cellDate > nextWeek) { 
 
    $(this).closest("td").addClass("green"); 
 
    } 
 
});
.red { 
 
    background: red; 
 
} 
 

 
.yellow { 
 
    background: yellow; 
 
} 
 

 
.green { 
 
    background: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <td>07/07/2017</td> 
 
    <td>07/08/2017</td> 
 
    <td>23/07/2017</td> 
 
</table>