使用Javascript / jQuery的:根据数据的属性值重新排序的div [英] Javascript/jQuery: Reordering divs according to data-attribute values
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/14160498/sort-element-by-numerical-value-of-data-attribute\">Sort通过数据的数值元素属性
我要根据他们设置数据属性重组的div,从最高整数到最低。现在,我所有的数据推到一个数组和排序的,但我不知道如何着手。我怎么可以用它来重新组织他们的父母DIV中的div?
I want to reorganize divs according to a data attribute set on them, ranging from highest integer to lowest. Right now, I push all the data into an array and sort that but I'm not sure how to proceed. How can I use this to reorganize divs inside their parent div?
var prices = new Array();
$(this).children('.listing-item').each(function() {
var price = parseInt($(this).attr('data-listing-price'));
prices.push(price)
});
prices.sort(function(a,b){return b-a});
这让我像139,129,129,109,109,84例如数组。现在我的想法通过的div是循环的另一个时间这样的选择:
This gets me an array like 139,129,129,109,109,84 for example. Now my idea was to loop through the divs another time with a selector like this:
$('.listing-item[data-listing-price="' + prices[0] + '"]')
但我不知道如何移动的div(最高数据属性整数DIV应该移动到顶部,等等。任何想法?
but I'm not sure how to move the divs (the div with the highest data-attribute integer should move to the top and so on. Any idea?
推荐答案
下面是解决方案
HTML
<div id="list">
<div class="listing-item" data-listing-price="2">2</div>
<div class="listing-item" data-listing-price="3">3</div>
<div class="listing-item" data-listing-price="1">1</div>
<div class="listing-item" data-listing-price="4">4</div>
</div>
JS:
var divList = $(".listing-item");
divList.sort(function(a, b){
return $(a).data("listing-price")-$(b).data("listing-price")
});
$("#list").html(divList);
的jsfiddle:
JSFiddle:
http://jsfiddle.net/bittu4u4ever/ezYJh/1/
这篇关于使用Javascript / jQuery的:根据数据的属性值重新排序的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!