Jquery – 排序DIV的孩子的innerHTML

我有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’?

和这个插件接近做我需要的(因为它可以处理孩子的属性),但它似乎并没有像孩子的内部HTML:http://tinysort.sjeiti.com/

任何帮助将赞赏这个noob。

解决方法

要直接使用子值而不使用插件来执行此操作,您可以使用类似以下内容
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以适应插件

看看这个demo:http://jsfiddle.net/6guj9/

在示例中,我们首先将价格和样式值添加为持有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"});

更改排序顺序和键可以通过简单地传递不同的配置对象来完成。链接演示展示了一种方法来做到这一点,但你可能想出一个更好的方案,以满足您的需要。

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...