Sort HTML list with HTML content using JQuery

前端 未结 2 695
春和景丽
春和景丽 2021-01-15 14:01

Is it possible to sort the list bellow from the lower number to the bigger number, keeping each li content?

  • 39 <
相关标签:
2条回答
  • 2021-01-15 14:45

    Your function should be like this.

    function numOrdDesc(a, b) {
        var aTxt = parseInt($(a)[0].innerText, 10);
        var bTxt = parseInt($(b)[0].innerText, 10);
        return (bTxt - aTxt);
    }
    

    DEMO

    0 讨论(0)
  • 2021-01-15 15:01

    Try below code,

    $(function() {
        $('button').click(function() {
            var liContents = [];
            $('ul li').each(function() {
                liContents.push($(this).html());
            });
            liContents.sort(liSorter);
            $('ul li').each(function() {
                $(this).html(liContents.pop());
            });
        });
    });
    
    /*
      Below function is kind of a workaround for the listed HTMl
      you need to update it if you have proper HTML.
    */
    function liSorter(a, b) {
        return (parseInt(b) - parseInt(a));
    }
    

    DEMO

    Edit: Updated your markup a little for a better code,

    1. Wrapped those number with span tags like <span class="num">39</span>
    2. Updated sorter function as below,

    Code:

    function numOrdDesc(a, b) {
        var aTxt = parseInt($(a).find('.num').text(), 10);
        var bTxt = parseInt($(b).find('.num').text(), 10);
        return (bTxt - aTxt);
    }
    

    DEMO

    0 讨论(0)
提交回复
热议问题