我试图从几个因素中对div列表进行排序,我已经将代码更改为更简单,但我仍然没有得到所需的结果。
我希望能够按照几个"分数排序我的产品"还有名字。我只能按一个分数排序。我想用两个不同的数据集对div进行排序。
任何人都可以看到我做错了吗?
jQuery的:
$(document).ready(function () {
$(".product-box").show();
$('#sortScore').click(function () {
var sortVar = "score";
var divList = $(".product-box");
divList.sort(function (a, b) {
return $(b).data(sortVar) - $(a).data(sortVar)
});
$(".wrapper").html(divList);
});
$('#sortName').click(function () {
var sortVar = "name";
var divList = $(".product-box");
divList.sort(function (a, b) {
return $(b).data(sortVar) - $(a).data(sortVar)
});
$(".wrapper").html(divList);
});
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='sortScore'>Score</div>
<div id='sortName'>Name</div>
<div class='wrapper'>
<div class='product-box' style='height:100px; width:100px; float:left;' data-name='Product 1' data-score='1.26'>
<p class='productInfo' style='float:left;'>
<strong>Product 1</strong>
<br />Score: 1.26</p>
</div>
<div class='product-box' style='height:100px; width:100px; float:left;' data-name='Another Product' data-score='5.43'>
<p class='productInfo' style='float:left;'>
<strong>Another Product</strong>
<br />Score: 5.43</p>
</div>
<div class='product-box' style='height:100px; width:100px; float:left;' data-name='Serious Product' data-score='-1.87'>
<p class='productInfo' style='float:left;'>
<strong>Serious Product</strong>
<br />Score: -1.87</p>
</div>
<div class='product-box' style='height:100px; width:100px; float:left;' data-name='Is this your product?' data-score='3.33'>
<p class='productInfo' style='float:left;'>
<strong>Is this your product?</strong>
<br />Score: 3.33</p>
</div>
<div class='product-box' style='height:100px; width:100px; float:left;' data-name='A Product' data-score='0.25'>
<p class='productInfo' style='float:left;'>
<strong>A Product</strong>
<br />0.25</p>
</div>
&#13;
答案 0 :(得分:0)
按分数排序似乎有效。问题是按名称排序时:
divList.sort(function (a, b) {
return $(b).data(sortVar) - $(a).data(sortVar)
});
...这失败了,因为你不能从另一个字符串中减去一个字符串。
divList.sort(function (a, b) {
return $(a).data(sortVar).localeCompare($(b).data(sortVar))
}