我有结果页面。每个div都有id,包含事件日期(Ymd)。我怎样才能通过子div事件日期对“结果”div中的div进行排序,并在日期为<或=今天?这应该很容易,但我不太擅长jquery。能够改变“今天”可变时区也是非常好的。
<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>
感谢您的帮助:)
答案 0 :(得分: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);
答案 1 :(得分: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>