jQuery jQuery表格排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3160277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery table sort
提问by tony noriega
I have a very simple HTML table with 4 columns:
我有一个非常简单的 HTML 表格,有 4 列:
Facility Name, Phone #, City, Specialty
I want the user to be able to sort by Facility Nameand Cityonly.
我希望用户只能按设施名称和城市进行排序。
How can I code this using jQuery?
如何使用 jQuery 对此进行编码?
采纳答案by James
If you want to avoid all the bells and whistles then may I suggest this simple sortElements
plugin. Usage:
如果你想避免所有的花里胡哨,那么我可以推荐这个简单的sortElements
插件。用法:
var table = $('table');
$('.sortable th')
.wrapInner('<span title="sort this column"/>')
.each(function(){
var th = $(this),
thIndex = th.index(),
inverse = false;
th.click(function(){
table.find('td').filter(function(){
return $(this).index() === thIndex;
}).sortElements(function(a, b){
if( $.text([a]) == $.text([b]) )
return 0;
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function(){
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
And a demo.(click the "city" and "facility" column-headers to sort)
和一个演示。(单击“城市”和“设施”列标题进行排序)
回答by Nick Grealy
I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.
我遇到了这个,并认为我会投入我的 2 美分。单击列标题以升序排序,再次单击以降序排序。
- Works in Chrome, Firefox, Opera AND IE(8)
- Only uses JQuery
- Does alpha and numeric sorting - ascending and descending
- 适用于 Chrome、Firefox、Opera 和 IE(8)
- 只使用 JQuery
- 字母和数字排序 - 升序和降序
$('th').click(function(){
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
table, th, td {
border: 1px solid black;
}
th {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><th>Country</th><th>Date</th><th>Size</th></tr>
<tr><td>France</td><td>2001-01-01</td><td>25</td></tr>
<tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>
<tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>
<tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>
<tr><td>USA</td><td></td><td>-6</td></tr>
</table>
** Update: 2018
** 更新:2018
- For those that are interested, I've provided an ES6 Plain Javascript solution here.
- 对于那些感兴趣的人,我在这里提供了一个ES6 Plain Javascript 解决方案。
回答by bpeterson76
By far, the easiest one I've used is: http://datatables.net/
到目前为止,我用过的最简单的一个是:http: //datatables.net/
Amazingly simple...just make sure if you go the DOM replacement route (IE, building a table and letting DataTables reformat it) then make sure to format your table with <thead>
and <tbody>
or it won't work. That's about the only gotcha.
非常简单……只要确保您使用 DOM 替换路线(IE,构建一个表并让 DataTables 重新格式化它)然后确保使用<thead>
和格式化您的表,<tbody>
否则它将不起作用。这是唯一的问题。
There's also support for AJAX, etc. As with all really good pieces of code, it's also VERY easy to turn it all off. You'd be suprised what you might use, though. I started with a "bare" DataTable that only sorted one field and then realized that some of the features were really relevant to what I'm doing. Clients LOVE the new features.
还有对 AJAX 等的支持。对于所有非常好的代码片段,也很容易将其全部关闭。不过,你会惊讶于你可能会使用什么。我从只对一个字段进行排序的“裸”数据表开始,然后意识到某些功能与我正在做的事情确实相关。客户喜欢新功能。
Bonus points to DataTables for full ThemeRoller support....
奖励指向 DataTables 以获得完整的 ThemeRoller 支持....
I've also had ok luck with tablesorter, but it's not nearly as easy, not quite as well documented, and has only ok features.
我在使用 tablesorter 时也很幸运,但它并不那么容易,没有很好的文档记录,并且只有 ok 的功能。
回答by Ravi Ram
We just started using this slick tool: https://plugins.jquery.com/tablesorter/
我们刚刚开始使用这个灵巧的工具:https: //plugins.jquery.com/tablesorter/
There is a video on its use at: http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx
有一个关于其使用的视频:http: //www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx
$('#tableRoster').tablesorter({
headers: {
0: { sorter: false },
4: { sorter: false }
}
});
With a simple table
用一张简单的桌子
<table id="tableRoster">
<thead>
<tr>
<th><input type="checkbox" class="rCheckBox" value="all" id="rAll" ></th>
<th>User</th>
<th>Verified</th>
<th>Recently Accessed</th>
<th> </th>
</tr>
</thead>
回答by cartbeforehorse
My answer would be "be careful". A lot of jQuery table-sorting add-ons only sort what you pass to the browser. In many cases, you have to keep in mind that tables are dynamic sets of data, and could potentially contain zillions of lines of data.
我的回答是“小心”。许多 jQuery 表排序附加组件只对传递给浏览器的内容进行排序。在许多情况下,您必须牢记表是动态数据集,并且可能包含数以百万计的数据行。
You do mention that you only have 4 columns, but much more importantly, you don't mention how many rows we're talking about here.
你确实提到你只有 4 列,但更重要的是,你没有提到我们在这里谈论的行数。
If you pass 5000 lines to the browser from the database, knowing that the actual database-table contains 100,000 rows, my question is: what's the point in making the table sortable? In order to do a proper sort, you'd have to send the query back to the database, and let the database (a tool actually designed to sort data) do the sorting for you.
如果您从数据库向浏览器传递 5000 行,并且知道实际的数据库表包含 100,000 行,我的问题是:使表可排序有什么意义?为了进行适当的排序,您必须将查询发送回数据库,并让数据库(一种实际设计用于对数据进行排序的工具)为您进行排序。
In direct answer to your question though, the best sorting add-on I've come across is Ingrid. There are many reasons that I don't like this add-on ("unnecessary bells and whistles..." as you call it), but one of it's best features in terms of sort, is that it uses ajax, and doesn't assume that you've already passed it all the data before it does its sort.
不过,直接回答您的问题,我遇到的最好的排序插件是 Ingrid。我不喜欢这个附加组件的原因有很多(你称之为“不必要的花里胡哨……”),但就排序而言,它最好的功能之一是它使用 ajax,并且不不要假设您在排序之前已经将所有数据传递给它。
I recognise that this answer is probably overkill (and over 2 years late) for your requirements, but I do get annoyed when developers in my field overlook this point. So I hope someone else picks up on it.
我认识到这个答案对于您的要求来说可能是矫枉过正(并且晚了 2 年多),但是当我所在领域的开发人员忽略这一点时,我确实很生气。所以我希望其他人接受它。
I feel better now.
我现在感觉好多了。
回答by cartbeforehorse
I love this accepted answer, however, rarely do you get requirements to sort html and not have to add icons indicating the sorting direction. I took the accept answer's usage example and fixed that quickly by simply adding bootstrap to my project, and adding the following code:
我喜欢这个公认的答案,但是,您很少需要对 html 进行排序,而不必添加指示排序方向的图标。我采用了接受答案的使用示例,并通过简单地向我的项目添加引导程序并添加以下代码来快速修复该问题:
<div></div>
<div></div>
inside each <th>
so that you have a place to set the icon.
在每个内部,<th>
以便您有一个设置图标的地方。
setIcon(this, inverse);
setIcon(this, inverse);
from the accepted answer's Usage, below the line:
从接受的答案的用法,在该行下方:
th.click(function () {
th.click(function () {
and by adding the setIcon method:
并通过添加 setIcon 方法:
function setIcon(element, inverse) {
var iconSpan = $(element).find('div');
if (inverse == false) {
$(iconSpan).removeClass();
$(iconSpan).addClass('icon-white icon-arrow-up');
} else {
$(iconSpan).removeClass();
$(iconSpan).addClass('icon-white icon-arrow-down');
}
$(element).siblings().find('div').removeClass();
}
Here is a demo. --You need to either run the demo in Firefox or IE, or disable Chrome's MIME-type checking for the demo to work. It depends on the sortElements Plugin, linked by the accepted answer, as an external resource. Just a heads up!
这是一个演示。--您需要在 Firefox 或 IE 中运行演示,或者禁用 Chrome 的 MIME 类型检查才能使演示工作。它取决于 sortElements 插件,由接受的答案链接,作为外部资源。只是抬头!
回答by Julian
This is a nice way of sorting a table:
这是对表格进行排序的好方法:
$(document).ready(function () {
$('th').each(function (col) {
$(this).hover(
function () {
$(this).addClass('focus');
},
function () {
$(this).removeClass('focus');
}
);
$(this).click(function () {
if ($(this).is('.asc')) {
$(this).removeClass('asc');
$(this).addClass('desc selected');
sortOrder = -1;
} else {
$(this).addClass('asc selected');
$(this).removeClass('desc');
sortOrder = 1;
}
$(this).siblings().removeClass('asc selected');
$(this).siblings().removeClass('desc selected');
var arrData = $('table').find('tbody >tr:has(td)').get();
arrData.sort(function (a, b) {
var val1 = $(a).children('td').eq(col).text().toUpperCase();
var val2 = $(b).children('td').eq(col).text().toUpperCase();
if ($.isNumeric(val1) && $.isNumeric(val2))
return sortOrder == 1 ? val1 - val2 : val2 - val1;
else
return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
});
$.each(arrData, function (index, row) {
$('tbody').append(row);
});
});
});
});
table, th, td {
border: 1px solid black;
}
th {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr><th>id</th><th>name</th><th>age</th></tr>
<tr><td>1</td><td>Julian</td><td>31</td></tr>
<tr><td>2</td><td>Bert</td><td>12</td></tr>
<tr><td>3</td><td>Xavier</td><td>25</td></tr>
<tr><td>4</td><td>Mindy</td><td>32</td></tr>
<tr><td>5</td><td>David</td><td>40</td></tr>
</table>
The fiddle can be found here:
https://jsfiddle.net/e3s84Luw/
小提琴可以在这里找到:https:
//jsfiddle.net/e3s84Luw/
The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code
解释可以在这里找到:https: //www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code
回答by SeanDowney
Here's a chart that may be helpful deciding which to use: http://blog.sematext.com/2011/09/19/top-javascript-dynamic-table-libraries/
这是一个图表,可能有助于决定使用哪个:http: //blog.sematext.com/2011/09/19/top-javascript-dynamic-table-libraries/
回答by rapttor
This one does not hang up the browser/s, easy configurable further:
这个不挂浏览器,方便进一步配置:
var table = $('table');
$('th.sortable').click(function(){
var table = $(this).parents('table').eq(0);
var ths = table.find('tr:gt(0)').toArray().sort(compare($(this).index()));
this.asc = !this.asc;
if (!this.asc)
ths = ths.reverse();
for (var i = 0; i < ths.length; i++)
table.append(ths[i]);
});
function compare(idx) {
return function(a, b) {
var A = tableCell(a, idx), B = tableCell(b, idx)
return $.isNumeric(A) && $.isNumeric(B) ?
A - B : A.toString().localeCompare(B)
}
}
function tableCell(tr, index){
return $(tr).children('td').eq(index).text()
}
回答by Dennis Golomazov
@Nick Grealy's answeris great, but it does not take into account possible rowspan
attributes of the table header cells (and probably the other answers don't do it either). Here is an improvement of the @Nick Grealy's answer which fixes that. Based on this answertoo (thanks @Andrew Orlov).
@Nick Grealy 的答案很好,但它没有考虑rowspan
表头单元格的可能属性(可能其他答案也没有考虑)。这是@Nick Grealy 的答案的改进,它解决了这个问题。也基于此答案(感谢@Andrew Orlov)。
I've also replaced the $.isNumeric
function with a custom one(thanks @zad) to make it work with older jQuery versions.
我还用自定义$.isNumeric
函数替换了该函数(感谢 @zad),使其适用于较旧的 jQuery 版本。
To activate it, add class="sortable"
to the <table>
tag.
要激活它,请添加class="sortable"
到<table>
标签。
$(document).ready(function() {
$('table.sortable th').click(function(){
var table = $(this).parents('table').eq(0);
var column_index = get_column_index(this);
var rows = table.find('tbody tr').toArray().sort(comparer(column_index));
this.asc = !this.asc;
if (!this.asc){rows = rows.reverse()};
for (var i = 0; i < rows.length; i++){table.append(rows[i])};
})
});
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index);
return isNumber(valA) && isNumber(valB) ? valA - valB : valA.localeCompare(valB);
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() };
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function get_column_index(element) {
var clickedEl = $(element);
var myCol = clickedEl.closest("th").index();
var myRow = clickedEl.closest("tr").index();
var rowspans = $("th[rowspan]");
rowspans.each(function () {
var rs = $(this);
var rsIndex = rs.closest("tr").index();
var rsQuantity = parseInt(rs.attr("rowspan"));
if (myRow > rsIndex && myRow <= rsIndex + rsQuantity - 1) {
myCol++;
}
});
// alert('Row: ' + myRow + ', Column: ' + myCol);
return myCol;
};