我在按日期排序返回的XML数据时遇到了很多问题。日期存储为YYYY-MM-DD。我很难在网上找到任何关于这种特定日期格式的帮助。
这是我的js:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "database.xml",
dataType: "xml",
success: function (xml) {
$(xml).find("event").filter(function () {
return $(this).find("eventplace").text() == 'NEWCASTLE';
}).each(function () {
var title = $(this).find('eventname').text();
var venue = $(this).find('eventvenue').text();
var city = $(this).find('eventplace').text();
var date = $(this).find('eventdate').text();
$('<div class="items">' + title + '</div>').html(title + venue + city + date).appendTo('#comingup');
});
}
});
});
下面是我的XML示例:
<Root_Element>
<eventserie>
<event>
<eventname>LITTLE COMETS</eventname>
<eventvenue>O2 ACADEMY</eventvenue>
<eventplace>NEWCASTLE</eventplace>
<eventdate>2014-02-21</eventvdate>
</event>
<event>
<eventname>SYMPHONIC PICTURES</eventname>
<eventvenue>THE CLUNY</eventvenue>
<eventplace>NEWCASTLE</eventplace>
<eventdate>2014-03-10</eventvdate>
</event>
<event>
<eventname>LET'S BUY HAPPINESS</eventname>
<eventvenue>THINK TANK</eventvenue>
<eventplace>NEWCASTLE</eventplace>
<eventdate>2014-02-10</eventvdate>
</event>
</eventserie></Root_Element>
将时间戳存储在数据属性中,并将元素存储在数组中,然后在添加元素之前根据时间戳对数组进行排序:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "database.xml",
dataType: "xml",
success: function (xml) {
var items = [];
$(xml).find("event").filter(function () {
return $(this).find("eventplace").text() == 'NEWCASTLE';
}).each(function () {
var title = $(this).find('eventname').text();
var venue = $(this).find('eventvenue').text();
var city = $(this).find('eventplace').text();
var date = $(this).find('eventdate').text();
items.push(
$('<div />', {
'class' : 'items',
text : title + venue + city + date,
'data-d' : new Date(date).getTime()
})
);
});
items.sort(function(a, b) {
return $(a).data('d').localeCompare( $(b).data('d') );
});
$.each(items, function(idx, itm) {
$('#comingup').append(itm);
});
}
});
});
不需要向数组推送。将集合转换为对象数组并对其进行排序。变量xmlevents
演示了如何做到这一点。还要在循环之外声明变量var
。这只需要做一次。
$(document).ready(function () {
$.ajax({
type: "GET",
url: "database.xml",
dataType: "xml",
success: function (xml) {
var xmlevents = $(xml).find("event");
xmlevents.sort(function(a,b){
a = $(a).find("eventdate").text();
b = $(b).find("eventdate").text();
return (a.localeCompare(b));
}
var title, venue, city, date
xmlevents.each(function () {
title = $(this).find('eventname').text();
venue = $(this).find('eventvenue').text();
city = $(this).find('eventplace').text();
date = $(this).find('eventdate').text();
$('<div class="items">' + title + '</div>').html(title + venue + city + date).appendTo('#comingup');
});
});