排序数据属性 [英] Sorting data attributes
本文介绍了排序数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个函数,该函数应该按价格高->低的顺序对data-cost
数据属性进行排序.当data-cost
都具有相同数量的数字时,它可以正常工作,但是如果我添加具有不同数量的数字的data-cost
,则该功能将不再起作用.我想保持现在的结构,但是由于我对JS还是比较陌生,因此我对更多可重用的解决方案持开放态度.预先感谢您的帮助.
I wrote a function that's supposed to sort a data-cost
data attribute by price high -> low. It works fine when the data-cost
all have the same amount of numbers, but if I add data-cost
s that have different amounts of numbers, the function no longer works. I'd like to keep the same structure that I have now, but as I'm still relatively new to JS, I'm open to more reusable solutions. Thanks in advance for any help.
小提琴:
HTML:
<a id="sort" href="#">Price High to Low</a>
<ul class="returned-list">
<li data-cost="101">101</li>
<li data-cost="103">103</li>
<li data-cost="106">106</li>
<li data-cost="42">42</li>
</ul>
JS:
var sortHL = function () {
function compare(a,b) {
if (a.cost > b.cost)
return -1;
if (a.cost < b.cost)
return 1;
return 0;
}
var items = [];
$('.returned-list li').each(function() {
var item = {
cost: $(this).attr('data-cost'),
contents: $(this)[0].outerHTML
};
items.push(item);
});
items.sort(compare);
$('.returned-list').html('');
for(var i=0;i<items.length;i++) {
$('.returned-list').append(items[i].contents);
}
};
$('#sort').on('click', function () {
sortHL();
});
推荐答案
执行强制转换:
cost: Number($(this).attr('data-cost')),
这篇关于排序数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文