2014-01-10 108 views
0

我想提出一個事件的日期壓延,想添加一個類下一個即將到來的日期(最接近當前日期)如何添加一個類的元素與最接近的值

HTML

<div> 
    <div class=".date" id="9,18,2013">18th Sept 2013: Going Fishing</div> 
    <div class=".date" id="22,01,2014">22nd Jan 2014: Going on Holiday to Greece</div> 
    <div class=".date" id="16,02,2014">16th Feb 2014: Business Meeting</div> 
    <div class=".date" id="27,02,2014">27th Feb 2014: Sisters Birthday</div> 
</div> 

的JavaScript/jQuery的

var today = new Date(); 
    var a = $(".date").attr('id') 
    var b = a.split(","); 
    var c = new Date(b[2], b[0], b[1]); 

這種變化值作爲一個日期的ID,但我需要找到最近的一個變量「今天」

+0

元素是否會在有序 –

+0

你的HTML代碼看起來真的奇怪的。你爲什麼不使用數據屬性? http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html –

+0

但不是HTML5元素的數據屬性?這不會給我很好的瀏覽器交叉活動,因爲我正在創建的頁面需要覆蓋,即7/8 – navigator

回答

1

如果在例子中的元素進行排序,然後

<div> 
    <div class="date" id="18,9,2013">18th Sept 2013: Going Fishing</div> 
    <div class="date" id="22,01,2014">22nd Jan 2014: Going on Holiday to Greece</div> 
    <div class="date" id="16,02,2014">16th Feb 2014: Business Meeting</div> 
    <div class="date" id="27,02,2014">27th Feb 2014: Sisters Birthday</div> 
</div> 

var today = new Date(); 
//clear the time part 
today.setHours(0, 0, 0, 0); 
//need to remove the . from the class attribute of the elements 
$('.date').each(function() { 
    var parts = this.id.split(","); 
    var date = new Date(parts[2], parts[1], parts[0]); 
    if (date - today > 0) { 
     $(this).addClass('next'); 
     //return false to prevent the iteration of any other element 
     return false; 
    } 
}) 

演示:Fiddle

+0

這裏是一個[修改小提琴](http://jsfiddle.net/S73KL/3/),我在評論中提出了修改(使用有效的HTML'id's&糾正無效日期在示例中)。 – AeroX

+1

@AeroX謝謝:) –