2015-04-18 79 views
2

单击时,我尝试按升序对此类进行排序,然后再降序排列。当我单击它时,Sort按升序顺序工作正常,但对于降序不起作用。请帮我做这个工作。我认为这与我的else语句有关,因为if语句工作得很好。 :)jQuery排序不降序

$(".id").click(function(){ 
    var mylist = $('.sort'); 
    var listitems = mylist.children('tr').get(); 
    listitems.sort(function(a, b) { 
    var compA = $(a).text().toUpperCase(); 
    var compB = $(b).text().toUpperCase(); 
    if ((compA < compB) ? -1 : (compA > compB) ? 1 : 0){ 
     return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; 
    } else { 
     return (compB < compA) ? 1:(compB > compB)? 1 : 0; 
    } 
    }); 
    $.each(listitems, function(idx, itm) { mylist.append(itm); }); 
}); 
+1

你在第二个return语句中比较'compB'自身 – JLewkovich

+0

你的'if条件'没有意义 –

回答

0

你需要切换有关信息在点击的按钮或链接上排序方向,
例如,商店等data-sort-direction的数据属性,其取值为ascdesc0升序排序和1降序排序类型内排序方向。

因此,在点击您检索该属性值,你根据其当前值ascdesc01你的项目进行排序,然后在的.sort使用它()方法来决定你是否有返回1-10

if (an > bn) { 
    return sortDirection === "asc" ? 1 : -1; 
} 
if (an < bn) { 
    return sortDirection ==="asc" ? -1 : 1; 
} 
return 0; 

HTML

<button class="id" data-sort-direction="asc">Sort</button> 
<table id="sort" class="table"> 
    <tr data-name="John Doe"> 
     <td>Mr. John Doe</td> 
    </tr> 
    <tr data-name="Trent Richardson"> 
     <td>Mr. Trent Richardson</td> 
    </tr> 
    <tr data-name="Cindy Smith"> 
     <td>Ms. Cindy Smith</td> 
    </tr> 
    <tr data-name="Bill Williams"> 
     <td>Mr. Bill Williams</td> 
    </tr> 
    <tr data-name="Jane Doe"> 
     <td>Mrs. Jane Doe</td> 
    </tr> 
</table> 

JS

var mylist = $('#sort'), 
    listitems = mylist.children('tbody').children('tr'); 
$('.id').on('click', function (e) { 
    var button = $(this),sortDirection = button.data('sort-direction'); 
    // update data attribute for the next click 
    sortDirection === "asc"?button.data('sort-direction', "desc"):button.data('sort-direction', "asc"); 
    listitems.sort(function (a, b) { 
     var an = a.getAttribute('data-name'), 
      bn = b.getAttribute('data-name'); 
     if (an > bn) { 
      return sortDirection === "asc"?1:-1; 
     } 
     if (an < bn) { 
      return sortDirection ==="asc"?-1:1; 
     } 
     return 0; 
    }); 

    listitems.detach().appendTo(mylist); 
}); 

要当心,当您从<table>标签检索<tr>物品,甚至还有,如果你在你的HTML省略它的隐含<tbody>,所以你必须得到<tr>项目是这样的:

listitems = mylist.children('tbody').children('tr'); 

Fiddle with <tr>

Fiddle with <div>

+0

感谢您的帮助。 :) –

0

更改排序功能,这一点:

listitems.sort(function (a, b) { 
    var compA = $(a).text().toUpperCase(); 
    var compB = $(b).text().toUpperCase(); 
    if(compA < compB) { 
     return -1; 
    } else if(compA > compB) { 
     return 1; 
    } else { 
     return 0; 
    } 
}); 

您还可以使用内置的Array方法进行排序的数组:

var sortedArr = Array.prototype.sort(listitems); 
+0

这看起来更清晰,但是当我点击时,它升序,并且在下一次点击时不下降。我得到相同的结果。 –

+0

@DariusCastillo听起来好像它可能是算法之外的问题。我们需要示例HTML和数组数据。 – JLewkovich

+0

感谢您的帮助。 :) –