jQuery jQuery按数据属性中的日期排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7211704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery order by date in data attribute
提问by benhowdle89
If i have this markup:
如果我有这个标记:
<p data-date="Fri, 26 Aug 2011 20:58:39 GMT">item 1</p>
<p data-date="Fri, 24 Aug 2011 20:58:39 GMT">item 1</p>
<p data-date="Fri, 25 Aug 2011 20:58:39 GMT">item 1</p>
How could i use jQuery to order these P's by their data-date attribute?
我如何使用 jQuery 通过它们的数据日期属性对这些 P 进行排序?
Thanks
谢谢
回答by Joseph Marikle
Demo
演示
Super simple with an array sort:
使用数组排序超级简单:
$("p").sort(function(a,b){
return new Date($(a).attr("data-date")) > new Date($(b).attr("data-date"));
}).each(function(){
$("body").prepend(this);
})
Reverse order (in case I misunderstood you) is as easy as flipping the greater than symbol
逆序(以防我误解了你)就像翻转大于号一样简单
$("p").sort(function(a,b){
return new Date($(a).attr("data-date")) < new Date($(b).attr("data-date"));
}).each(function(){
$("body").prepend(this);
})
回答by AlienWebguy
function sortDates(a, b)
{
return new Date(b).getTime() - new Date(a).getTime();
}
var dates = [];
var _old;
$('p').each(function(){
_old = $(this).parent();
dates.push($(this).data('date'));
});
var sorted = dates.sort(sortDates);
var _new = $('<div/>').insertBefore(_old);
$.each(sorted,function(i,val){
$('p[data-date="' + val + '"]').appendTo(_new);
});
_old.remove();
Working demo: http://jsfiddle.net/AlienWebguy/JhgSw/
回答by Industrial Zombie
The custom function suggested in Joseph's answer (the currently accepted solution) should return a numeric value, not a boolean. See This other questionwhere this issue has already been raised showing that this function will not work in IE.
Joseph 的答案(当前接受的解决方案)中建议的自定义函数应该返回一个数值,而不是一个布尔值。请参阅已提出此问题的其他问题,表明此功能在 IE 中不起作用。
The "dates.compare(a,b)" function defined herelooks like a better fit for use in jQuery's sort method.
此处定义的“dates.compare(a,b)”函数看起来更适合在 jQuery 的 sort 方法中使用。