2015-04-22 61 views
1

我有結果頁面。每個div都有事件日期(Ymd)。我怎樣才能排序這些div的「結果」div由子div事件日期和消除div如果日期是<或=今天?這應該很容易,但我並不擅長jquery。另外,能夠改變「今天」可變時區將是非常好的。按日期排序div(這是div id)

<div class="results"> 
    <div class="item shadowbox route_entry" id="20150417"> 
     Content 
    </div> 
    <div class="item shadowbox route_entry" id="20150422"> 
     Content 
    </div> 
    <div class="item shadowbox route_entry" id="20150424"> 
     Content 
    </div> 
    <div class="item shadowbox route_entry" id="20150427"> 
     Content 
    </div> 
    <div class="item shadowbox route_entry" id="20150429"> 
     Content 
    </div> 
</div> 

感謝您的幫助:)

回答

2

這個片段過濾器各種你div的

// Get date string formatted as YYYYMMDD 
 
var date = new Date(); 
 
var dateString = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + (date.getDate())).slice(-2); 
 

 
var $results = $('.results'); 
 
var $items = $results.children('.item'); 
 

 
// Detach items from results container 
 
$items.detach(); 
 

 
// Filter items where date > today 
 
$items = $items.filter(function(i, item){ 
 
    return item.id > dateString; 
 
}); 
 

 
// Sort items by date 
 
$items.sort(function(a,b){ 
 
    return a.id > b.id; 
 
}); 
 

 
// Reappend filtered and sorted items back into container 
 
$items.appendTo($results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="results"> 
 
    <div class="item shadowbox route_entry" id="20150417"> 
 
     20150417 
 
    </div> 
 
    <div class="item shadowbox route_entry" id="20150422"> 
 
     20150422 
 
    </div> 
 
    <div class="item shadowbox route_entry" id="20150424"> 
 
     20150424 
 
    </div> 
 
    <div class="item shadowbox route_entry" id="20150427"> 
 
     20150427 
 
    </div> 
 
    <div class="item shadowbox route_entry" id="20150425"> 
 
     20150425 
 
    </div> 
 
</div>

+0

謝謝@sw_double作品恰到好處。我怎樣才能設置日期變量的時區? – MIC

+1

我想你最好的選擇是使用一些時區庫。 瞬間Timezone http://momentjs.com/timezone/或 timezone-js https://github.com/mde/timezone-js 查看此問題的更多信息 http://stackoverflow.com/questions/10087819 /轉換,日期到另一個,時區,在JavaScript的 –

3

您可以使用$.filter,像這樣

var today = new Date().getTime(), 
    $result = $('.results > .item').clone(true).filter(function() { 
     // get date 
     var date = $(this).attr('id').replace(/(\d{4})(\d{2})(\d{2})/,"$1-$2-$3");   
     // compare with current date, if <= today return true, and item will be in result, if return false item will be ignored 
     return new Date(date).getTime() > today; 
    }).sort(function (a, b) { 
     return +a.id - +b.id; 
    });; 

$('.results').html($result); 

Example

+0

工程:)感謝您的幫助:)它的工作原理,因爲我想:) – MIC