2013-03-26 14 views
2

感謝所有考慮我newbe問題。 我使用jQuery遍歷表並捕獲數組中的所有硬編碼日期。 我比較這些日期與Date.today();使用.isAfter()函數。 如果硬編碼日期在過去,它應該得到一個.css(「display」,「none」);jquery:迭代通過比較​​硬編碼日期</td>對Date.today()然後刪除日期<今天

<table> 
    <html> 
     <table> 
     <tr class="gig"> 

      <td class="gigDate">Mar 27 2013</td> 
      <td>the Saloon</td> 
      <td>Atlanta, Ga</td> 
      <td>$20 (2 passes)</td> 
      <td>button to purchase tix<td> 
     </tr> 

     <tr class="gig"><td class="gigDate"> ... date2 ..</td></tr> 
     <tr class="gig"><td class="gigDate"> ... date3 ..</td></tr> 
     <tr class="gig"><td class="gigDate"> ... date4 ect ..</td></tr> 
    </table> 

<script type="text/javascript"> 
$("document").ready(function() { 

var stringDate = []; //create array to hold elements 

var now = Date.today(); // create current date 

$('.gigDate').each(function (i, e) { //adds hardcoded dates to array 
stringDate.push($(e).text()); 
}); 

for(var y = 0; y < stringDate.length; y++){ 
var singleDate = Date.parse(stringDate[y]); //parse to milliseconds 
var compare = now.isAfter(singleDate);  //compare to today's date 

if(compare){ 
    $('.gig').css("display", "none"); //hide <tr class="gig"> 
             //if in the past 
     } 
}  
}); 
</script> 

循環邏輯似乎正常工作,但添加樣式display:none的if(語句)是重擊。 任何幫助將不勝感激。

+0

你可以提供一個[的jsfiddle(HTTP:/ /jsfiddle.net)例子? – Dom 2013-03-26 22:47:20

回答

0

當您嘗試隱藏單個行時,您只需隱藏所有行 - $('。gig')將選擇所有行,而不僅僅是您認爲應該的行。

在您測試日期的循環內移動您的邏輯。大致是這樣的(我改變了你的代碼儘可能少,可能仍然無法正常工作,還沒有檢查):

var now = Date.today(); // create current date 

$('.gigDate').each(function (i, e) { //adds hardcoded dates to array 
    var current = ($(e).text()); 
    var singleDate = Date.parse(current); //parse to milliseconds 
    var compare = now.isAfter(singleDate);  //compare to today's date 
    if(compare){ 
     // we want to hide the parent of td, not the td: 
     $(e).parent().css("display", "none"); //hide <tr class="gig"> 
             //if in the past 
    } 

}); 
+0

忘記了評論,@fdreger非常感謝,.parent().css()做到了這一點。 – 2013-06-28 21:04:25

0

我不知道這是isAfter函數,但可以直接比較日期。我想這會更容易。

0

是否有任何理由你過濾客戶端?似乎效率低下。你的html是硬編碼還是你有服務器端腳本?除非沒有其他選擇,否則您應該過濾預渲染結果。

0

即使比較工作你會隱藏與類「演出」什麼。

您可以通過從字符串中創建新的Date(xxxxxxx)來簡化此操作。然後,您可以使用'<'運算符進行比較。

假設你的演出日期是相同的格式,您的活動日期:

var now = new Date(); // create current date  
$('.gigDate').each(function (i, e) { 
    ele = $(this).html(); 
    gigDate = new Date(ele); 
    if (gigDate<now){ 
     $(this).hide(); 
    } 

}); 

你可以看到它在這裏工作:

http://jsfiddle.net/skelly/vzH8U/