表格排序練習
html代碼
<table id="tab">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody></tbody>
</table>
添加樣式
* { margin: 0; padding: 0; }
#tab { margin: 100px auto; text-align: center; list-style: none; }
#tab thead { font-weight: 100; background-color: skyblue; }
#tab thead th { width: 100px; padding-top: 5px; font-weight: 100; }
#tab tbody tr { height: 20px; font-size: 14px; font-weight: 100; }
#tab tbody tr td { padding: 5px; }
#tab tbody tr:nth-child(odd) td{ background-color: #cfcfcf; }
#tab tbody tr:nth-child(even) td{ background-color: #f1f1ee; }
#tab tbody tr:hover td{ background-color: pink; }
js代碼
<script>
/* 待填入表格的數據 */
const jsonData = [
{
name: "蕾姆",
age: 18,
email: "1234567890@qq.com",
phone: "13245637823",
},
{
name: "emt",
age: 14,
email: "4123456890@qq.com",
phone: "13800026574"
},
{
name: "拉姆",
age: 18,
email: "4123456780@qq.com",
phone: "18723456423",
},
{
name: "菜月昴",
age: 20,
email: "5234567890@qq.com",
phone: "13800993302"
},
{
name: "貝蒂",
age: 17,
email: "2234567890@qq.com",
phone: "15802193302"
}
]
const oTbody = document.querySelector('tbody')
const thes = document.querySelectorAll('th')
/* 插入數據 */
function insertData() {
let str = ''
if (jsonData && jsonData.length !== 0) {
for (let i = 0; i < jsonData.length; i++) {
str += `<tr>`
for (let key in jsonData[i]) {
str += `<td>${jsonData[i][key]}</td>`
}
str += `</tr>`
}
}
oTbody.innerHTML = str
}
insertData()
/* 給th綁定點擊事件 */
for (let i = 0; i < thes.length; i++) {
thes[i].onclick = function () {
//從新排序
reSort.call(this, i)
}
}
/* 從新排序 */
function reSort(i) {
const trs = oTbody.children
let trArr = [].slice.call(trs, 0)
//默認降序排序
trArr.sort((a, b) => {
let innerA = a.children[i].innerHTML.slice(0, 5)
let innerB = b.children[i].innerHTML.slice(0, 5)
if (isNaN(innerA)) {
return innerA.localeCompare(innerB)
} else {
return innerB - innerA
}
})
//再次點擊再次排序
if (this.flag === 'asc') {
trArr.reverse()
this.flag = 'desc'
} else {
this.flag = 'asc'
}
//排序後從新渲染
let frg = document.createDocumentFragment()
for (let i = 0; i < trArr.length; i++) {
frg.appendChild(trArr[i])
}
oTbody.appendChild(frg)
}
</script>