Jquery - sort DIV's by innerHTML of children

后端 未结 4 736
醉话见心
醉话见心 2020-12-02 08:41

I\'ve got html that looks something like this:

Price:20
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 09:26

    To do this sort directly using the child values and without a plugin, you could use something like:

    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);
    }
    

    Sorting by price can then be done as such:

    sortUsingNestedText($('#sortThis'), "div", "span.price");
    

    The function is parametrised so that it can be easily reused with other divs and different sort keys.

    Here's a demo: http://jsfiddle.net/tc5dc/


    Using the tinysort plugin

    Alternatively, if you can benefit from the features provided by the tinysort plugin (mentioned in question), you could dynamically augment your divs to suit the plugin.

    Check out this demo: http://jsfiddle.net/6guj9/

    In the example, we first add the price and style values as data attributes of the holding 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());
    });
    

    We're then free to use tinysort to sort on the relevant attributes. Sorting by price would be simply:

    $("#sortThis>div").tsort({attr:"data-price"});
    

    Changing the sort order and keys can be done by simply passing in different config objects. The linked demo shows one way to do this, but you can probably come up with a better scheme to suit your needs.

提交回复
热议问题