Sorting li's in jQuery loaded divs
I make a 3 language website, where I need to sort the comments from all the 3 languages, that they are visible on every language's pages. http://www.polinapasztircsak.com/guestboo开发者_如何学运维k/
I tried loading with jQuery .load
method, and it works, but the problem is that it loads the separate languages in div
s (I didn't know other way to load and append it) and I can't sort the comment li
s outside their div
s. Here is the code:
var commEng = $('<div></div>').load('../guestbook/ .comment');
var commHun = $('<div></div>').load('../vendegkonyv/?lang=hu .comment');
var commIta = $('<div></div>').load('../libro-ospiti/?lang=it .comment');
$(".commentlist").empty().append(commEng).append(commHun).append(commIta);
Do you have some other suggestion how I could load in the li
s, that I have them together in the same ul
, and then which method or plug-in to use for sorting that.
You can try using $.get
or any other ajax functions to load the comments, then sort them using Javascript's sort
function. The code would look something like this:
var loaded = 0,
sites = 3,
comments = [];
function getComments(url){
$.get(url, function(data){
comments[loaded++] = ($(data).find('.comment'));
if(loaded === sites){
var insert = comments[0];
for(var i = 1; i < comments.length; i++){
insert = insert.add(comments[i]);
}
$('.commentlist').append(insert.sort(function(a, b){
var dateA = new Date($.trim($(a).find('.comment-meta:first a').text()).replace('at', '') + ' GMT'),
dateB = new Date($.trim($(b).find('.comment-meta:first a').text()).replace('at', '') + ' GMT');
return dateB.getTime() - dateA.getTime();
}));
}
});
}
getComments('../guestbook/');
getComments('../vendegkonyv/?lang=hu');
getComments('../libro-ospiti/?lang=it');
This will sort the jQuery element received through ajax with sort()
by passing in a function that will compare the dates of the comments scraped from the comment meta. Also remember that div
s in ul
unordered list is not valid HTML.
精彩评论