我有以下代码:
<div>
<div id="1">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="2">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="3">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>
我需要根据 min-price 属性对这3个div进行排序。在Jquery有可能吗?我找到了sort()
函数,但我无法正确使用它。谢谢。
答案 0 :(得分:0)
您可以使用.sort()
功能:
$('div[id]').sort(function (a, b) {
var minprice1 = parseInt( $(a).find('span').attr('min-price'));
var minprice2 = parseInt( $(b).find('span').attr('min-price'));
return (minprice1 < minprice2 ) ? -1 : (minprice1 > minprice2 ) ? 1 : 0;
});
答案 1 :(得分:0)
试试这个:
$(document).ready(function() {
$("div[id]").each(function(number,ele) {
$("div[id]").not($(ele)).each(function(index,el){
a = $(ele).find("span").attr("min-price");
b = $(el).find("span").attr("min-price");
if( parseFloat(a) > parseFloat(b) )
$(ele).insertAfter($(el));
})
})
})
&#13;
<div>
<div id="1">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="2">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="3">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
&#13;
答案 2 :(得分:0)
function sortElements(element, prop, sortDescending) {
var arrElements = [], origElements = [];
$.each(element, function(){
arrElements.push($(this).attr(prop));
origElements.push($(this).attr(prop));
});
arrElements.sort();
if(sortDescending)
arrElements.reverse();
for(var i = 0, l = arrElements.length; i < l; i++)
$("#sortDiv").append($("#"+arrElements[i]));
$("#divOrig").html($("#sortDiv").html());
$("#sortDiv").remove();
}
sortElements($("#divOrig span"), "min-price", true);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOrig">
<div id="50">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="30">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="40">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>
<div id="sortDiv" style="display:none" ></div>
&#13;