我有看起来像这样的html:
<div id="sortThis">
<div id="1">Price:<span class="price">20</span><span class="style">blue</span></div>
<div id="2">Price:<span class="price">23</span><span class="style">red</span></div>
<div id="3">Price:<span class="price">10</span><span class="style">red</span></div>
<div id="4">Price:<span class="price">29</span><span class="style">green</span></div>
<div id="5">Price:<span class="price">35</span><span class="style">blue</span></div>
</div>
我希望能够按.price或.style进行排序
我怀疑这篇文章部分回答了我的问题:Sort Divs in Jquery Based on Attribute 'data-sort'?
而且该插件几乎可以满足我的需要(因为它可以处理子属性),但似乎不及子类的innerHTML:http://tinysort.sjeiti.com/
这个菜鸟将不胜感激。
最佳答案
要直接使用子值而不使用插件来进行这种排序,可以使用以下方法:
function sortUsingNestedText(parent, childSelector, keySelector) {
var items = parent.children(childSelector).sort(function(a, b) {
var vA = $(keySelector, a).text();
var vB = $(keySelector, b).text();
return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
});
parent.append(items);
}
然后可以按价格排序:
sortUsingNestedText($('#sortThis'), "div", "span.price");
该函数已参数化,因此可以轻松地与其他div和不同的排序键一起使用。
这是一个演示:http://jsfiddle.net/tc5dc/
使用tinysort插件
另外,如果您可以受益于tinysort插件提供的功能(有问题),则可以动态扩展div以适合该插件。
查看此演示:http://jsfiddle.net/6guj9/
在示例中,我们首先添加
price
和style
值作为保持div的数据属性:var sortThis = $('#sortThis').children("div");
sortThis.each(function() {
var p = $(this);
p.attr("data-price", p.find("span.price").text());
p.attr("data-style", p.find("span.style").text());
});
然后,我们可以随意使用tinysort对相关属性进行排序。按价格排序将很简单:
$("#sortThis>div").tsort({attr:"data-price"});
只需传递不同的配置对象即可更改排序顺序和键。链接的演示演示了执行此操作的一种方法,但是您可能会想出一种更好的方案来满足您的需求。