<div id='panelb'>
<div class='item'>Ćao</div>
<div class='item'>Bella</div>
<div class='item'>Mare</div>
</div>
我使用以下代码对上述div进行排序:
js
var items = $('.item').get();
items.sort(function(a, b) {
return $(a).text().localeCompare($(b).text());
});
$('#panelb').append(items);
它有效,但我需要检查项目是否已分类,之前上述程序。
类似的东西:
if ('.item').are(:sorted) {alert ('sorted');}
else {alert ('not sorted');}
有什么想法吗?
答案 0 :(得分:1)
var testOutOfOrder = function(item, idx) {
if (idx === 0) return false;
return ($(item).text().localeCompare($(items[idx - 1]).text()) < 0);
};
if (items.some(testOutOfOrder)) {
... do sort here
}
这将测试是否有任何故障。如果您的环境不支持“某些()”,那么您可以为循环和中断做一个标准。方法
var testOutOfOrder = function(items) {
var isOutOfOrder = false;
for (var i = 0; i < items.length; i++) {
if ($(item).text().localeCompare($(items[idx - 1]).text()) < 0) {
isOutOfOrder = true;
break;
}
}
return isOutOfOrder;
};
if (testOutOfOrder(items)) {
... sort logic here
}
答案 1 :(得分:1)
嗯,根据 Mike McCaughan
的评论,我只是想尝试一下:
$(document).ready(function() {
var items = $('.item'), // get the items
clonedItems = items.clone(), // copy the items
isSorted = false;
// sort the copy
clonedItems.sort(function(a, b) {
return $(a).text().localeCompare($(b).text());
});
// compare items
isSorted = $.arrayCompare(items, clonedItems);
// if not sorted from the first time, show them sorted
if (!isSorted) {
$('#panelb').html(clonedItems);
}
});
// Obtained from: http://stackoverflow.com/a/5186565/1178686
jQuery.extend({
arrayCompare: function(arrayA, arrayB) {
if (arrayA.length != arrayB.length) {
return false;
}
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
var a = jQuery.extend(true, [], arrayA);
var b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="panelb">
<div class="item">Ćao</div>
<div class="item">Bella</div>
<div class="item">Mare</div>
</div>