我正在使用jQuery(ajax)来解析和XML文件,将数据添加到数组中,对其进行排序,然后显示它。一切都在Firefox中运行良好,但它在Chrome中表现不正常(即它只是部分排序)
以下是页面:http://teachwritework.com/part-time-teaching-jobs.php
我已经在这里待了3个多小时而且我被困住了。如果有人能以我的方式指出错误,我将非常感激。我是JS / Ajax的新手,所以要温柔。我的代码如下:
$(document).ready(function () {
var dates = [];
$.ajax({
type: "GET",
url: "jobs-for-teachers.xml",
dataType: "xml",
success: xmlParser
});
}); /* End get-xml */
function xmlParser(xml) {
var dates = [];
$(xml).find("job").each(function () {
dates.push({
jobtitle: $(this).find("title").text(),
jobsource: $(this).find("source").text(),
posted: $(this).find("posted").text(),
locale: $(this).find("location").text(),
employer: $(this).find("employer").text(),
comp: $(this).find("comp").text(),
schedule: $(this).find("schedule").text(),
reqs: $(this).find("reqs").text(),
desc: $(this).find("desc").text(),
contact: $(this).find("contact").text()
});
}); /* End parsing xml */
/* Updated code to sort in reverse chronological order */
dates.sort(function(a,b){
if(a.posted<b.posted) return 1;
if(a.posted>b.posted) return -1;
return 0;
});
var html=[];
$.each(dates, function() {
html.push(
'<h2>' + this.jobtitle
+ '</h2><br><h5>Posted: </h5>' + this.posted
+ '<br><br><h5>Location: </h5><div class="tfield">' + this.locale
+ '<br></div><h5>Employer: </h5><div class="tfield">' + this.employer
+ '<br></div><h5>Compensation: </h5><div class="tfield">' + this.comp
+ '<br></div><h5>Schedule: </h5><div class="tfield">' + this.schedule
+ '<br></div><h5>Description: </h5><div class="tfield">' + this.desc
+ '<br><br></div><h5>Requirements: </h5><div class="tfield">' + this.reqs
+ '<br></div><h5>Contact: </h5><div class="tfield">' + this.contact
+ '<br><br></div><h5>Source: </h5><div class="tfield">' + this.jobsource
+ '</div><br class="clr"><br><br><hr><br><br>'
);
});
$('.listings').append(html.join(''));
} / *结束xml-parser * /
答案 0 :(得分:0)
请参阅此问题:Sorting an array of JavaScript objects
所以如果你加上这个:
var sort_by = function(field, reverse, primer){
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B) ? -1 :
(A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
}
然后您可以这样排序:
// Date sort
dates.sort(sort_by('posted', false, function(a){return new Date(a)}));