大多时候我们对於资料感兴趣在极端值的区域,也最边缘的最大或最小的前几名,而我们可以用排序的功能使它们列於表格的最上方。这个同样在架构上可以参考W3Schools的范例,但其中演算法和机制我们加以改良。
首先是排序的主体,我们选用bubble的方式来实现,这可以参考此范例,其中我们以rows[i].getElementsByTagName("td")[colIndex].innerHTML来抓取当下这一个元素以及用rows[i + 1].getElementsByTagName("td")[colIndex].innerHTML来抓取相邻的下一个元素,而innerHTML抓出的结果会是string,所以我们用个额外的function将如果是number的转成number。
若想要由小到大排列时,但当下元素若大於下一个元素,则需交换这两个元素的位置,反之若为由大到小亦然,此时再用parentNode.insertBefore此function来互换位置。
第二个比较特别的功能是,我们可以让由大到小(dir="desc")以及由小到大(dir="asc")在点表头时做切换。作法为预设由大到小,若序列已经是由大到小,则改为由小到大再重复一次流程:
function sortTable(tableId, colIndex) {
let i, currContent, nextContent, shouldSwitch = 0;
let table = document.getElementById(tableId);
let rows = table.rows;
let switching = true;
let dir = "desc";
let fullRowLength = rows.length - 1;
let rowLength = fullRowLength
// Make a loop that will continue until no switching has been done:
while (switching) {
// Start by saying: no switching is done:
switching = false;
/* Loop through all table rows (except the first, which contains table headers): */
for (i = 1; i < rowLength; i++) {
shouldSwitch = false;
// Get the two elements you want to compare, one from current row and one from the next:
// if case-insensitive, add toLowerCase()/toUpperCase()
currContent = stringToNumber(rows[i].getElementsByTagName("td")[colIndex].innerHTML);
nextContent = stringToNumber(rows[i + 1].getElementsByTagName("td")[colIndex].innerHTML);
/* Check if the two rows should switch place, based on the direction, asc or desc: */
if (dir == "asc") {
if (currContent > nextContent) {
shouldSwitch = true;
}
} else if (dir == "desc") {
if (currContent < nextContent) {
shouldSwitch = true;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark that a switch has been done: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
/* If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again. */
if (!switching && dir == "desc" && rowLength == fullRowLength) {
dir = "asc";
switching = true;
} else {
rowLength --;
}
}
}
接下来是HTML的部分,我们需要在表头()的属性中,加上点了会触发(onclick)来呼叫刚所写的sortTable,在之前day2所写的生成表格的function也可以更新加入这个功能(注解为原本code),而那时留下的keyName这个伏笔的变数就是这时用的,可以给入对应表格的id:
// content += "<th>" + cell + "</th>";
content += "<th onclick=\"sortTable(\'" + keyName + "\', " + count_cell + ")\">" + cell + "</th>" ;
最後一样是今日结果:
数学由大到小排序:
数学由小到大排序:
程序由大到小排序:
程序由小到大排序:
等我研究完怎麽上传动画再更新。
<<: Innodb资料页结构-Part1(使用者纪录、空闲空间、页面中最小与最大的纪录)
>>: IOS、Python自学心得30天 Day-3 TensorFlow 模组
前言 在更新Linkedkin 个人档案的时候 偶然发现他有技术检定测验 如果总成绩在前30%,会发...
“It's only because of their stupidity that they'r...
聊完有线上网,我们接着从 Wi-Fi 开始,到提供行动上网不同世代,看看这些服务是怎麽出现的,又用了...
package com.example.touth; public class listdata ...