我有一个非常简单的HTML表,有4列:
Facility Name, Phone #, City, Specialty
我希望用户只能按设施名称和城市进行排序。
我如何使用jQuery编码这个?
我有一个非常简单的HTML表,有4列:
Facility Name, Phone #, City, Specialty
我希望用户只能按设施名称和城市进行排序。
我如何使用jQuery编码这个?
当前回答
另一种对HTML表进行排序的方法。(基于W3.JS HTML Sort)
/* Facility Name */ $('#bioTable th:eq(0)').addClass("control-label pointer"); /* Phone # */ $('#bioTable th:eq(1)').addClass("not-allowed"); /* City */ $('#bioTable th:eq(2)').addClass("control-label pointer"); /* Specialty */ $('#bioTable th:eq(3)').addClass("not-allowed"); var collection = [{ "FacilityName": "MinION", "Phone": "999-8888", "City": "France", "Specialty": "Genetic Prediction" }, { "FacilityName": "GridION X5", "Phone": "999-8812", "City": "Singapore", "Specialty": "DNA Assembly" }, { "FacilityName": "PromethION", "Phone": "929-8888", "City": "San Francisco", "Specialty": "DNA Testing" }, { "FacilityName": "iSeq 100 System", "Phone": "999-8008", "City": "Christchurch", "Specialty": "gDNA-mRNA sequencing" }] $tbody = $("#bioTable").append('<tbody></tbody>'); for (var i = 0; i < collection.length; i++) { $tbody = $tbody.append('<tr class="item"><td>' + collection[i]["FacilityName"] + '</td><td>' + collection[i]["Phone"] + '</td><td>' + collection[i]["City"] + '</td><td>' + collection[i]["Specialty"] + '</td></tr>'); } .control-label:after { content: "*"; color: red; } .pointer { cursor: pointer; } .not-allowed { cursor: not-allowed; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://www.w3schools.com/lib/w3.js"></script> <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" /> <p>Click the <strong>table headers</strong> to sort the table accordingly:</p> <table id="bioTable" class="w3-table-all"> <thead> <tr> <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(1)')">Facility Name</th> <th>Phone #</th> <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(3)')">City</th> <th>Specialty</th> </tr> </thead> </table>
其他回答
这一个不会挂起浏览器,容易配置进一步:
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()
}
我们刚刚开始使用这个灵巧的工具:https://plugins.jquery.com/tablesorter/
有一个关于它的使用的视频: http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx
$('#tableRoster').tablesorter({
headers: {
0: { sorter: false },
4: { sorter: false }
}
});
用一个简单的表格
<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>
@Nick Grealy的回答很好,但它没有考虑到表头单元格可能的行跨度属性(可能其他答案也没有这样做)。下面是对@Nick Grealy的回答的改进,解决了这个问题。也是基于这个答案(谢谢@Andrew Orlov)。
我也替换了$。isNumeric函数带有自定义的函数(感谢@zad),以使其适用于较旧的jQuery版本。
要激活它,在<table>标记中添加class="sortable"。
$(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;
};
这是一个排序表的好方法:
$(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>
提琴可以在这里找到: https://jsfiddle.net/e3s84Luw/
解释如下: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code
如果你想避免所有的铃铛和口哨,那么我可以建议这个简单的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;
});
});
还有一个演示。(点击“城市”和“设施”列标题进行排序)