jQuery - order DIVs depending on an extracted number of a classname
I have a list of DIVs, like this :
<div id="list">
<div class="classA classB SORT-4.2"><div>4</div></div>
<div class="classA SORT-3.3"><div&开发者_如何学Gogt;3</div></div>
<div class="classC classD classE SORT-5.1"><div>5</div></div>
<div class="classB classC SORT-1.5"><div>1</div></div>
<div class="classA class B class C SORT-2.4"><div>2</div></div>
</div>
and I want to sort them, using jQuery
Server-side, I can define the wanted order, and include this order in the class names :
SORT-4.2
I want to be able to call either the first order (in my example this DIV will be in the 4th position), or the second order (it will be in the 2nd position) : that explains the "4.2"
So if I call OrderDIV(1)
I will have this :
1
2
3
4
5
and if I call OrderDIV(2)
I will have this :
5
4
3
2
1
(I will need to add more orders, like : SORT-4.2.5.6.2)
As you can see DIVs can have multiple classes, only the pattern SORT-
defines the class used to sort
Thank you VERY MUCH for your help!
Create a function that accepts the divs and the order number (1,2,etc).
Convert the divs from a jQuery object to an Array of DOM elements.
Use a regular expression to extract the proper information from the className and overwrite the Array so it looks like:
arr[0] = {num:4, el:/* the element */}
arr[1] = {num:2, el:/* the element */}
arr[2] = {num:3, el:/* the element */}
Then sort on a.num
and b.num
.
Finally iterate the array, appending each element.
function sort( divs, order ) {
var arr = divs.toArray(),
len = arr.length,
parent = divs.parent(),
i = 0;
while( i < len ) {
var num = arr[ i ].className.match(/(?:SORT-([\d.]+))/)[1].split('.');
arr[ i ] = {num:num[ order - 1 ],el:arr[ i ]};
i++;
}
arr.sort(function(a,b) {
return a.num - b.num;
});
i = 0;
while( i < len ) {
parent.append( arr[i].el );
i++;
}
}
Result is:
Example: http://jsfiddle.net/TsArJ/10/
sort( $('#list > div'), 3 ); // 1,2,3,4,5
maybe some like this:
$(function(){
function sortDIV(){
var divs=$("div[class*=SORT]").clone();
divs.sort(function(pDiv,fDiv){
var pNumber=parseInt($(pDiv).attr("class").match(/SORT-(.*)/)[1].replace(".",""));
var fNumber=parseInt($(fDiv).attr("class").match(/SORT-(.*)/)[1].replace(".",""));
return pNumber<fNumber;
})
var parent=$($("div[class*=SORT]")[0]).parent();
parent.empty();
divs.each(function(index,div){
$(div).appendTo(parent);
})
}
sortDIV();
})
more info: http://jsfiddle.net/apvjN/20/
精彩评论