正在寻找一个javascript解决方案来重新排序div

我在页面中有一些div显示相同类型的不同内容,例如优惠,现在优惠有结束时间,还有发布时间,如果用户想按结束时间或发布时间订购,则应重新订购。

我正在寻找一个可以做到这一点的JavaScript解决方案,Ext JS或JQuery下的任何特定库都可以工作

以下是这些div的外观

所以我想能够根据data-sortN对这些div进行排序,N是一个整数

编辑:好的,既然您已经提供了一些HTML,这里的javascript代码将按所需的列号对特定的HTML进行排序:

 function sortByDataItem(containerID, dataNum) { var values = []; $("#" + containerID + " .item").each(function(index) { var item = {}; item.index = index; item.obj = this; item.value = $(this).data("sort" + dataNum); values.push(item); }); values.sort(function(a, b) {return(b.value - a.value);}); var container = $("#" + containerID); for (var i = 0; i < values.length; i++) { var self = $(values[i].obj); self.detach(); container.prepend(self); } return; } $("#sort").click(function() { var sortValue = $("#sortColumn").val(); if (sortValue) { sortValue = parseInt(sortValue, 10); if (sortValue && sortValue > 0 && sortValue <= 3) { sortByDataItem("container", sortValue); return; } } $("#msg").show(1).delay(5000).fadeOut('slow'); }); 

您可以在jsFiddle中看到它的工作原理: http : //jsfiddle.net/jfriend00/JG32X/


既然你没有给我们任何HTML继续,我已经制作了自己的HTML并向你展示了如何使用jQuery进行排序:

HTML:

 
Popcorn
$5.00
Peanuts
$4.00
Cookie
$3.00
Beer
$5.50
Soda
$4.50

Javascript(在页面加载后运行):

 $("#sort").click(function() { var prices = []; // find all prices $("#productList .price").each(function(index) { var str = $(this).text(); var item = {}; var matches = str.match(/\d+\.\d+/); if (matches && matches.length > 0) { // parse price and add it to the prices array item.price = parseFloat(matches[0]); item.row = $(this).closest(".row").get(0); item.index = index; prices.push(item); } }); // now the prices array has all the prices in it // sort it using a custom sort function prices.sort(function(a, b) { return(a.price - b.price); }); // now pull each row out and put it at the beginning // starting from the end of the prices list var productList = $("#productList"); for (var i = prices.length - 1; i >= 0; i--) { var self = $(prices[i].row); self.detach(); productList.prepend(self); } }); 

而且,一个jsFiddle显示它在行动: http : //jsfiddle.net/jfriend00/vRdrA/ 。

我用jfriend00的答案做了一个小jqueryPlugin:

 (function($){ $.fn.sortChildrenByDataKey = function(key, desc){   var i, els = this.children().sort(function(a, b) {return (desc?1:-1)*($(a).data(key) - $(b).data(key));});   for (i = 0; i < els.length; i++) {     this.prepend($(els[i]).detach());   } return this; }; })(jQuery); 

你的HTML:

 
...
...
...

用法:

 $('div#myContainer').sortChildrenByDataKey('myKey', true_or_false); 

容器的子元素可以是任何元素。 唯一重要的是,他们是直接的孩子并拥有数据X键。

谢谢你,jfriend00 !!