排序问题:我有李,我想通过点击Asc和Desc来排序

时间:2015-06-17 11:49:11

标签: jquery html sorting

我想按列表Ascending和Descending顺序排序。 当我点击升序时,它将按降序排序降序排序,应使用jQuery或任何其他javascript库应用排序。 jsfiddle上添加的示例代码请点击链接

jsfiddle

<p><a href="#" id="asc">Ascending</a> | <a href="#" id="desc">Descending</a></p>
<ul id="test">
<li style="display: inline-block; border: 1px solid transparent;">

    <a href="/redlands/gourmet-pizza-shoppe" rel="962" class="to_business"><span>Gourmet Pizza Shoppe</span></a>
</li>
<li style="display: inline-block; border: 1px solid transparent;">

    <a href="/redlands/therons-frozen-custard" rel="1020"
       class="to_business"><span>Theron's Frozen Custard</span></a>
</li>
<li style="display: inline-block; border: 1px solid transparent;">

    <a href="/redlands/mu-restaurant-and-bar" rel="1024" class="to_business"><span>Mu Restaurant and Bar</span></a>
</li>
<li style="display: inline-block; border: 1px solid transparent;">

    <a href="/redlands/redlands-underground" rel="1026" class="to_business"><span>Redlands Underground</span></a>
</li></ul>

2 个答案:

答案 0 :(得分:2)

试试这个: -

$(function() {
$('#asc,#desc').click(function() {
    var $sort = this;
    var $list = $('#test');
    var $listLi = $('li',$list);
    $listLi.sort(function(a, b){
        var keyA = $(a).find('span').text();
        var keyB = $(b).find('span').text();
        if($($sort).is('#asc')){
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA < keyB) ? 1 : 0;
        }
    });
    $.each($listLi, function(index, row){
        $list.append(row);
    });
  });
});

<强> Demo

答案 1 :(得分:1)

$(document).ready(function() {
    $('#asc, #desc').on('click', function() {

        var sortMethod = $(this).attr('id');
        var options = $('ul#test > li');

        options.sort(function(a, b){
            var aText = $(a).find('a span').text();
            var bText = $(b).find('a span').text();
            if(sortMethod == 'asc'){
                return aText.localeCompare(bText);
            }else{
                return bText.localeCompare(aText);
            }
        });

        $('ul#test').append(options);
    });
});