视递美食网
您的当前位置:首页用jquery.sortElements实现table排序_javascript技巧

用jquery.sortElements实现table排序_javascript技巧

来源:视递美食网


项目中要实现table排序的功能。

网上有很多解决方案,很多都基于jQuery。

jquery.tablesorter,大小17KB,不过他的首页在ie10下兼容性有点问题。
DataTables,大小75KB,功能强大,带分页,搜索等功能。
还有插件叫sortElements,很小巧,只有3KB,兼容性也不错,而且在Github上有818个星。

最后我选择用sortElements,实现很简单:

1. 引入jQuery
代码如下:


2. 引入sortElements.js
代码如下:


3. js 代码
代码如下:
$(document).ready(function(){
var table = $('#mytable');//table的id
$('#sort_header')//要排序的headerid
.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){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function(){
return this.parentNode;
});
inverse = !inverse;

});
});
});

4. html代码
代码如下:













...
Facility name Phone # City Speciality
CCC 00001111 Amsterdam GGG

显示全文