正如你所看到的,它按字母顺序和数字顺序排列95%的div,但它的错误。不知道为什么会那样做。如果您多次按下按钮,您将看到我的意思。谢谢!
似乎总是第一,第二和第二第4盒。
var $divs = $("div.box");
$('#alphBnt').on('click', function() {
var alphabeticallyOrderedDivs = $divs.sort(function(a, b) {
return $(a).find("h1").text() > $(b).find("h1").text();
});
$("#container").html(alphabeticallyOrderedDivs);
});
$('#numBnt').on('click', function() {
var numericallyOrderedDivs = $divs.sort(function(a, b) {
return $(a).find("h2").text() > $(b).find("h2").text();
});
$("#container").html(numericallyOrderedDivs);
});

body {
background: #eee;
font-family: sans-serif;
}
.box {
background: lightgreen;
height: 200px;
width: 200px;
display: inline-block;
}
.box h1 {
color: white;
font-size: 1em;
text-align: center;
}
.box h2 {
color: black;
font-size: 2.5em;
text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<button id="alphBnt">Alphabetical</button>
<button id="numBnt">Numerical</button>
<div id="container">
<div class="box">
<h1>A</h1>
<h2>7/10</h2>
</div>
<div class="box">
<h1>B</h1>
<h2>8/10</h2>
</div>
<div class="box">
<h1>C</h1>
<h2>6.8/10</h2>
</div>
<div class="box">
<h1>D</h1>
<h2>8/10</h2>
</div>
<div class="box">
<h1>E</h1>
<h2>510.25</h2>
</div>
<div class="box">
<h1>F</h1>
<h2>5,512</h2>
<div class="box">
<h1>G</h1>
<h2>7/10</h2>
</div>
<div class="box">
<h1>H</h1>
<h2>8/10</h2>
</div>
<div class="box">
<h1>I</h1>
<h2>6.8/10</h2>
</div>
<div class="box">
<h1>J</h1>
<h2>8/10</h2>
</div>
<div class="box">
<h1>K</h1>
<h2>510.25</h2>
</div>
<div class="box">
<h1>L</h1>
<h2>5,512</h2>
</div>
&#13;
答案 0 :(得分:4)
sort()
的回调函数需要将负值,0或正值作为返回值,因为您返回一个布尔值,它将false
视为0,其被评估为等于。如果您尝试此排序功能,您将看到它的工作原理:
$('#alphBnt').on('click', function () {
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
var at = $(a).find("h1").text();
var bt = $(b).find("h1").text();
return at > bt ? 1 : (at < bt ? -1 : 0);
});
$("#container").html(alphabeticallyOrderedDivs);
});
答案 1 :(得分:1)
我更新了您的脚本以更正排序问题。
var $divs = $("div.box");
$('#alphBnt').on('click', function () {
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
return case_insensitive_comp($(a).find("h1").text(), $(b).find("h1").text());
});
$("#container").html(alphabeticallyOrderedDivs);
});
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return eval($(a).find("h2").text()) > eval($(b).find("h2").text());
});
$("#container").html(numericallyOrderedDivs);
});
function case_insensitive_comp(strA, strB) {
return strA.toLowerCase().localeCompare(strB.toLowerCase());
}