jQuery – 在向其添加行之后对表进行排序
我有2个表,一个表有2列,另一个表有1列。 单击某行时,该行将从表中删除,并且新TR将添加到对应表的末尾。 现在我想按字母顺序排序。
像tablesorter这样的jQuery插件对于我想要做的事情来说总是有点过分。 有没有一种简单的方法可以对表格进行排序?
编辑: 小提琴
在这里你有一个简单的表格分类器和一个小提琴演示 :
HTML
he stackoverflow by vote post And clicking up did
JQUERY
$('.sort-table').click(function(e) { e.preventDefault(); // prevent default behaviour var sortAsc = $(this).hasClass('asc'), // ASC or DESC sorting $table = $('#sort-table'), // cache the target table DOM element $rows = $('tbody > tr', $table); // cache rows from target table body $rows.sort(function(a, b) { var keyA = $('td',a).text(); var keyB = $('td',b).text(); if (sortAsc) { return (keyA > keyB) ? 1 : 0; // A bigger than B, sorting ascending } else { return (keyA < keyB) ? 1 : 0; // B bigger than A, sorting descending } }); $rows.each(function(index, row){ $table.append(row); // append rows after sort }); });
我没有足够的声誉来评论Zuul的答案,但它并不总是有效。 检查这个小提琴:
$('.sort-table').click(function(e) { e.preventDefault(); // prevent default button click behaviour var sortAsc = $(this).hasClass('asc'), // ASC or DESC $table = $('#sort-table'), // cache the target table DOM element $rows = $('tbody > tr', $table); // cache all rows from the target table body $rows.sort(function(a, b) { var keyA = $('td',a).text(); var keyB = $('td',b).text(); if (sortAsc) { return (keyA > keyB) ? 1 : 0; // A bigger than B, sorting ascending } else { return (keyA < keyB) ? 1 : 0; // B bigger than A, sorting descending } }); $rows.each(function(index, row){ $table.append(row); // append rows after sort }); });
Text 2003-01-27.pdf Text 2004-03-23.pdf Text 2004-04-01.pdf Text 2004-12-31.pdf Text 2010-04-14.pdf Text 2011-02-07.pdf Medic 2004-08-24.pdf Bank 2009-10-06.pdf Family 2010-10-19.pdf Statement 2002-03-06.pdf Statement 2002-03-06.pdf Statement 2004-06-30.pdf Statement 2010-03-31.pdf Next.pdf School 2002-03-04.pdf School 2003-06-23.pdf School 2010-06-10.pdf Deal 2002-03-04.pdf Deal 2002-06-03.pdf Deal 2003-06-03.pdf Vacation 2009-08-10.pdf Vacation 2007-03-26.pdf Vacation 2009-08-10.pdf Vacation 2008-03-19.pdf Vacation 2009-03-23.pdf Vacation 2012-09-21.pdf Vacation 2012-09-17.pdf Vacation 2014-09-25.pdf Vacation 2014-10-23.pdf Work 2004-06-21.pdf Work 2009-09-09.pdf Work 2010-05-01.pdf AGR 2002-03-05.pdf AGR 2004-10-28.pdf AGR 2005-11-22.pdf AGR 2011-01-20.pdf