i've built this sample code based on a real problem I have in an application. I've got a custom sort procedure to sort jQuery arrays. A container contains a list of items with special attributes.
For sorting:
Somehow Firefox knows how to sort but IE doesn't. Can somebody tell me what isn't working properly?
(you can copy-paste the html below into a empty .html file, it should work immediately)
<html>
<head>
<script type="text/javascript"
src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
jQuery.fn.sort = function() {
return this.pushStack( [].sort.apply( this, arguments ), []);
}
function DoTheSort() {
//Fetch elements in jQueryElement
var sortableArray = $('#sortables').find('div.sortable');
//Clear the sortables container
$('#sortables').empty();
//Sort the array
var sortedArray = $(sortableArray).sort(sortProcedure);
//Append sorted items
jQuery.each(sortedArray, function() {
alert($(this).attr("sortvalue"));
$('#sortables').append(this);
});
}
function sortProcedure(a, b) {
var value1 = parseInt($(a).attr("sortvalue"));
var value2 = parseInt($(b).attr("sortvalue"));
return value1 > value2;
}
</script>
</head>
<body>
<a href="javascript:DoTheSort();">Sort</a>
<div id="sortables">
<div class="sortable" sortvalue="5">5</div>
<div class="sortable" sortvalue="1">1</div>
<div class="sortable" sortvalue="4">4</div>
<div class="sortable" sortvalue="1">1</div>
<div class="sortable" sortvalue="2">2</div>
<div class="sortable" sortvalue="9">9</div>
<div class="sortable" sortvalue="3">3</div>
</div>
</body>
</html>
Your sort procedure is subtly wrong: you need to account for equalities as well, and boolean is not the correct return type (see addendum).
Do this:
return value1 - value2;
instead of:
return value1 > value2;
Addendum:
The general form of a sort comparison function f(A,B) needs to return > 0 if A > B, < 0 if A < B, and 0 if no alteration needs to occur. Returning a boolean gets you caught by falsey values not representing what you think they do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With