Ordering elements by number in JQuery
how could I arrange the following div's by the value in the attribute amount with jquery? Thanks.
<a href="#" id="id1" class="lTest" amount="12">
<div>abcd1</div>
<a/>
<a href="#" id="id2" class="lTest" amount="64">
<div>abcd2</div>
<a/>
<a href="#" id="id3" class="lTest" amount="32">
<开发者_如何学JAVAdiv>abcd3</div>
<a/>
<a href="#" id="id4" class="lTest" amount="8">
<div>abcd4</div>
<a/>
This one should work.
<!doctype html>
<html>
<head>
<script src='jquery.js'></script>
<script>
$(document).ready(init);
function init() {
var parent = $('#someid');
var children = $('a', parent);
children.sort(function(a, b) {
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
})
$.each(children, function(i, child) {
parent.append(child);
});
}
</script>
</head>
<body>
<div id="someid">
<a href="#" class="lTest" amount="12"><div>abcd2</div></a>
<a href="#" class="lTest" amount="64"><div>abcd4</div></a>
<a href="#" class="lTest" amount="32"><div>abcd3</div></a>
<a href="#" class="lTest" amount="8"><div>abcd1</div></a>
</div>
</body>
</html>
[Edit] Replaced by a SSCCE to prove it's working. I've changed x in abcdx to the expected ordering. You should end up with abcd1, abcd2, abcd3 and abcd4 in this order.
Try this:
var links = $('a.lTest').sort( function(a,b) { return $(a).attr('amount') - $(b).attr('amount'); } );
for ( var i = 1; i < links.length; i++ ) {
links.eq(i-1).insertBefore( links.eq(i) );
}
first, assume the tags are surrounded by a div (id ="testDiv")
Sorry, my initial way of doing this is wrong...
DO NOT DO THIS: BROKEN!!! (See edit below)
var testDiv = $('#testDiv'); var children = testDiv.children('.lTest'); children.each(function() {$(this).remove();}); var testArray = $.makeArray(children); testArray.sort(function(a,b){ return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'); });
children.each(function() {testDiv.append(this);});
EDIT: THIS IS WORKING VERSION:
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest').remove();
children = children.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
});
testDiv.append(children);
Your first comment on Tinister's answer indicates that your test page doesn't know anything about JQuery. Make sure you are properly including JQuery in your tests and that the HTML is correctly constructed. Then you will probably find that one of the other answers works.
John
精彩评论