根据元素的data属性对div排序 [英] Sort divs bases on element's data attribute
本文介绍了根据元素的data属性对div排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要能够根据子元素的data-price属性对div列表进行排序. 这是我的标记:
I need to be able to sort a list of divs based on the data-price attribute of a sub element. This is my markup:
<div class="container">
<div class="terminal" data-price="195">
<h3>195</h3>
</div>
195 - I should come in 2nd.
</div>
<div class="container">
<div class="terminal" data-price="220">
<h3>220</h3>
</div>
220 - I should come in 3rd.
</div>
<div class="container">
<div class="terminal" data-price="130">
<h3>130</h3>
</div>
130 - I should come in 1st.
</div>
这是我到目前为止的脚本:
This is the script I have so far:
function sorter(a, b) {
return a.getAttribute('data-price') - b.getAttribute('data-price');
};
$(document).ready(function () {
var sortedDivs = $(".terminal").toArray().sort(sorter);
$.each(sortedDivs, function (index, value) {
$(".container", this).html(value);
//console.log(value);
});
});
结果应替换现有的标记.我就是不能上班.需要更改什么?
The result should replace the existing markup. I just can't get to work. What needs to be changed?
推荐答案
以下内容应该起作用:
$('.container').sort(function (a, b) {
return $(a).find('.terminal').data('price') - $(b).find('.terminal').data('price');
}).each(function (_, container) {
$(container).parent().append(container);
});
尽管我建议不要在没有共同父母的情况下这样做.如果还有其他子节点,则$(container).parent().append(container);
部分可能会出现问题.
though I recommend against doing this without a common parent. The $(container).parent().append(container);
part could be problematic if there are other child nodes present.
演示: http://jsbin.com/UHeFEYA/1/
或者,您可以执行以下操作:
alternatively you could do this:
$('.terminal').sort(function (a, b) {
return $(a).data('price') - $(b).data('price');
}).map(function () {
return $(this).closest('.container');
}).each(function (_, container) {
$(container).parent().append(container);
});
这篇关于根据元素的data属性对div排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文