按日期排序jQuery Ajax Json forEach数据

时间:2017-07-03 14:23:49

标签: javascript jquery json ajax

我从JSON文件中获取数据。但我的代码读取并附加它,因为它写在文件中我想按日期对数据进行排序。

我试过这个:但是不起作用= /

$('.1article').sort(function (a, b) {
var contentA =parseInt( $(a).attr('data-date'));
var contentB =parseInt( $(b).attr('data-date'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
})

我的Ajax代码

$(document).ready(function() { 
function imgError(image) {
    image.onerror = "";
    image.src = "img/S0-voiture-de-l-annee-2017-les-sept-finalistes-nos-pronostics-391613.jpg";
    return true;
}
$.ajax({
type: "GET",
url: 'http://s604712774.onlinehome.fr/videdressing/text.json',
dataType: 'json',
success: function(data) {
data.forEach(function(post) {
var fds = new Date(post.date) ;

var datetimeposted = new Date(post.date); 
var datetime = datetimeposted.getDate() + "/" + (datetimeposted.getMonth()+1)  + "/" + datetimeposted.getFullYear();

var currentdate = new Date(); 
var now = new Date(currentdate.getFullYear() + ", " + ( '0' +(currentdate.getMonth()+1)).slice( -2 )  + ", " + ( '0' +currentdate.getDate()));
var result = (now - fds) ;
var days = result / 1000 / 60 / 60 / 24 ;

if ("14" < days)  {
$(".id" + post.id).css('display','none');
};

$( '.articles' ).prepend( ' <div class="1article col s12 m6 l4 id' + post.id + '" data-date="' + fds +'"> <div class="card"> <div class="card-content"> <span class="titlevente activator grey-text text-darken-4 titlevente">' + post.title +'</span><br><span class="titlevente activator grey-text text-darken-4 titlevente" style="font-size:10px !important;">' + post.category +' | ' + datetime +'</span> </div><div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="img/S0-voiture-de-l-annee-2017-les-sept-finalistes-nos-pronostics-391613.jpg"> </div><div class="card-content"> <span class="metadesc activator grey-text text-darken-4">' + post.ville +' | ' + post.prix +'€<i class="material-icons right">more_vert</i></span> </div><div class="card-reveal"> <span class="card-title grey-text text-darken-4">' + post.title +'<i class="material-icons right">close</i></span> <p>' + post.decription +'</p><div class="incarddata"> <i id="delete" class="material-icons h32">&#xE872;</i> <a href=""><i class="material-icons h32">share</i></a> <a href="mailto:' + post.mail +'"><i class="material-icons h32">&#xE158;</i></a> <a href="tel:' + post.telephone +'"><i class="material-icons h32">&#xE0CD;</i></a> </div></div></div></div>' );  
});
}
});
});

你可以在这里查找 - &gt; https://jsfiddle.net/ds77bmu9/1/

1 个答案:

答案 0 :(得分:0)

我编辑了你的小提琴,你必须在迭代之前对数组进行排序。此外,您的排序功能不正确(在javascript中,您只需使用-减去日期):

success: function(data) {
    data.sort(function(a, b) {
        return new Date(b.date) - new Date(a.date);
    })
    foreach(data : ...)
}

这是你的小提琴修复。 https://jsfiddle.net/ds77bmu9/3/