内容介绍
jQuery实现表格排序,点击每一列表头,对tbody内容进行升序排序,非数字的使用Unicode编码进行排序。
一、代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>表格排序</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<style>
.missionTable {
width: 1200px;
font-size: 13px;
margin: 0 auto;
border: 0.3px solid #B9B9B9;
border-bottom: none;
}
.missionTable,
thead,
th,
tr,
td {
text-align: center;
border-collapse: collapse;
}
.missionTable thead {
border-radius: 6px 6px 0px 0px;
border-bottom: 1px solid #D5D5D5;
}
.missionTable th {
height: 49px;
line-height: 49px;
font-size: 14px;
font-family: PingFang SC;
color: #222222;
background: #FCFDFD;
border-right: 0.3px dashed #999;
cursor: pointer;
}
tbody tr {
background: #FFFFFF;
border-bottom: 0.4px solid rgba(151, 151, 151, 0.4);
}
tbody tr:hover {
background-color: rgba(0, 0, 0, 0.01);
}
.missionTable td {
height: 39px;
font-size: 14px;
font-family: PingFang SC;
color: #666666;
border-right: 1px solid #cdcdcd;
}
</style>
</head>
<body>
<table cellpadding="0" style="table-layout:fixed;" id="missionTable" class="missionTable" width="500">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>职位</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>张三</td>
<td>24</td>
<td>Web前端</td>
</tr>
<tr>
<td>6</td>
<td>李四</td>
<td>21</td>
<td>交互设计师</td>
</tr>
<tr>
<td>17</td>
<td>张大千</td>
<td>28</td>
<td>交互设计师</td>
</tr>
<tr>
<td>3</td>
<td>王二</td>
<td>24</td>
<td>C++程序员</td>
</tr>
<tr>
<td>22</td>
<td>马六</td>
<td>30</td>
<td>测试员</td>
</tr>
</tbody>
</table>
<script>
! function(window, document, $, undefined) {
$('th').on('click', function() {
let $this = $(this)
let index = $this.index()
let arr = []
$('tbody>tr').each(function(index, item) {
arr.push($(this))
})
arr.sort(function(a, b) {
if (isNaN(a.find(`td:eq(${index})`).html())) {
return a.find(`td:eq(${index})`).html().charCodeAt() - b.find(`td:eq(${index})`).html().charCodeAt()
} else {
return a.find(`td:eq(${index})`).html() - b.find(`td:eq(${index})`).html()
}
})
$('tbody').append(arr)
})
}(window, document, jQuery)
</script>
</body>
</html>
二、效果图
👇 👇 👇 👇 👇
编号排序后
注:
非数字的内容根据Unicode码进行排序;
标签:jQuery,表格排序
更多演示案例,查看 案例演示
_欢迎评论留言!