用jquery.sortElements实现table排序

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

用jquery.sortElements实现table排序

  2020-05-13 我要评论
项目中要实现table排序的功能。

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

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

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

1. 引入jQuery
复制代码 代码如下:

<script type="text/javascript" src="jquery.js"></script>

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

<script type="text/javascript" src="jquery.sortElements.js"></script>

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代码
复制代码 代码如下:

<table id="mytable">
<tr>
<th id="sort_header">Facility name</th>
<th>Phone #</th>
<th id="city_header">City</th>
<th>Speciality</th>
</tr>
<tr>
<td>CCC</td>
<td>00001111</td>
<td>Amsterdam</td>
<td>GGG</td>
</tr>
...
</table>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们