基于元素的数据属性对div进行排序
我需要能够根据子元素的data-price属性对div列表进行排序。 这是我的标记:
195
195 - I should come in 2nd. 220
220 - I should come in 3rd. 130
130 - I should come in 1st.
这是我到目前为止的脚本:
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); }); });
结果应该替换现有的标记。 我无法上class。 需要改变什么?
这是一个小提琴 。
以下应该工作:
$('.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);
如果存在其他子节点,则部分可能会有问题。
演示 : http : //jsbin.com/UHeFEYA/1/
或者你可以这样做:
$('.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); });
如果你想把它们放在body
,你可以这样做:
function sorter(a, b) { return a.getAttribute('data-price') - b.getAttribute('data-price'); }; var sortedDivs = $(".terminal").toArray().sort(sorter); $(".container").remove(); //removing the old values $.each(sortedDivs, function (index, value) { $('body').append(value); //adding them to the body });
生活演示: http : //jsfiddle.net/a2TzL/1/