如何创建 - 对列表进行排序
单击按钮按字母顺序对列表进行排序:
- Oslo
- Stockholm
- Helsinki
- Berlin
- Rome
- Madrid
创建排序函数
实例
<ul id="id01">
<li>Oslo</li>
<li>Stockholm</li>
<li>Helsinki</li>
<li>Berlin</li>
<li>Rome</li>
<li>Madrid</li>
</ul>
<script>
function sortList() {
var list, i, switching, b, shouldSwitch;
list =
document.getElementById("id01");
switching = true;
/* Make
a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is
done:
switching = false;
b =
list.getElementsByTagName("LI");
// Loop through all
list items:
for (i = 0; i < (b.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Check if the next
item should
switch place with the current
item: */
if (b[i].innerHTML.toLowerCase() >
b[i + 1].innerHTML.toLowerCase()) {
/* If next item is alphabetically lower than current item,
mark as a switch and break the loop: */
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
</script>
亲自试一试 »
升序和降序排序
第一次点击按钮,排序方向为升序(A到Z)。
再次点击,排序方向为降序(Z到A):
- Oslo
- Stockholm
- Helsinki
- Berlin
- Rome
- Madrid
实例
<ul id="id01">
<li>Oslo</li>
<li>Stockholm</li>
<li>Helsinki</li>
<li>Berlin</li>
<li>Rome</li>
<li>Madrid</li>
</ul>
<script>
function sortListDir() {
var list, i, switching, b, shouldSwitch, dir, switchcount = 0;
list
= document.getElementById("id01");
switching = true;
// 将排序方向设置为升序:
dir = "asc";
// 创建一个循环,直到没有切换完成:
while (switching) {
// 首先说:没有切换:
switching = false;
b = list.getElementsByTagName("LI");
// 遍历所有列表项:
for (i = 0; i < (b.length - 1); i++) {
// 首先说不应该切换:
shouldSwitch = false;
/* 检查下一个项目是否应该与当前项目交换位置,
基于排序方向(asc 或 desc):*/
if (dir == "asc") {
if (b[i].innerHTML.toLowerCase()
> b[i + 1].innerHTML.toLowerCase()) {
/* 如果下一项按字母顺序低于当前项,
标记为 switch 并打破循环:*/
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if
(b[i].innerHTML.toLowerCase() < b[i + 1].innerHTML.toLowerCase()) {
/* 如果下一项按字母顺序高于当前项,
标记为 switch 并打破循环: */
shouldSwitch= true;
break;
}
}
}
if (shouldSwitch) {
/* 如果已标记,请进行 switch
并标记已完成切换: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
// 每完成一次切换,将 switchcount 增加 1:
switchcount
++;
} else {
/* 如果没有进行切换并且方向为 "asc",
将方向设置为 "desc" 并再次运行 while 循环。 */
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
</script>
亲自试一试 »