页面结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body,
html {
padding: 0;
margin: 0;
font-size: 14px;
color: #000000;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
thead {
background: #3d444c;
color: #ffffff;
cursor: pointer;
}
td,
th {
border: 1px solid #e1e1e1;
padding: 0;
height: 30px;
line-height: 30px;
text-align: center;
}
</style>
<body>
<table>
<thead>
<tr onclick="changeSort(event)">
<th>id</th>
<th>price</th>
<th>sales</th>
</tr>
</thead>
<tbody id="jsList">
<tr>
<td>1</td>
<td>10.0</td>
<td>800</td>
</tr>
<tr>
<td>2</td>
<td>30.0</td>
<td>600</td>
</tr>
<tr>
<td>3</td>
<td>20.5</td>
<td>700</td>
</tr>
<tr>
<td>4</td>
<td>40.5</td>
<td>500</td>
</tr>
<tr>
<td>5</td>
<td>60.5</td>
<td>300</td>
</tr>
<tr>
<td>6</td>
<td>50.0</td>
<td>400</td>
</tr>
<tr>
<td>7</td>
<td>70.0</td>
<td>200</td>
</tr>
<tr>
<td>8</td>
<td>80.5</td>
<td>100</td>
</tr>
</tbody>
</table>
</body>
</html>
js代码
<script>
//排序方法
function sort(type, order) {
const jsList = document.querySelector('#jsList') //获取tbody节点
let trs = document.querySelectorAll('tbody>tr') //获取所有tr
trs = Array.prototype.slice.call(trs) //转化为新数组
//根据传过来的type排序
trs.sort(function (tr1, tr2) {
let a = tr1.children[obj[type]].innerHTML
let b = tr2.children[obj[type]].innerHTML
if (order == true) return a - b
else return b - a
})
//对dom结构重新排序
for (let i of trs) {
jsList.appendChild(i)//appendChild原节点存在 则移动位置
}
}
let ths = document.querySelectorAll('thead tr th') //获取表头列表
ths = Array.prototype.slice.call(ths)//转化为新数组
//存储类型对象
let obj = {}
ths.map((item, index) => {
obj[item.innerHTML] = index //{id: 0, price: 1, sales: 2}
})
let bol = [] //存储当前排序状态
for (let i in ths) {
bol[i] = false
}
bol[0] = true //默认第一列 递增排序
// sort('sales', 'true')
//点击表头改变排序
function changeSort(e) {
const type = e.target.innerHTML // 拿到点击对象值
const idx = obj[type] //拿到索引
// 调用sort方法
bol[idx] = !bol[idx]
sort(type, bol[idx]) //默认递增 再次点击递减
}
</script>