我现在才学习HTML,并且遇到了如何在w3schools上对列表进行排序[链接-> https://www.w3schools.com/howto/howto_js_sort_list.asp]
使用该链接中的代码,我将所有
杰西卡
伦敦
1975
亚伦
东京
1962
Peter
纽约
1958
现在,当我单击“排序”时,列表当然会按预期的方式按第一行的第一个字母排序,如下所示:
亚伦
东京
1962
杰西卡
伦敦
1975
彼得
纽约
1958
我想要的是再添加2个排序按钮;一个按第二行排序,另一个按第三行排序。我制作了一个图表以更好地描述我在说什么: https://i.imgur.com/uiPEYqs.png
有可能吗?让我知道,谢谢。
答案 0 :(得分:0)
修改示例,
使用sortList('2')
和sortList('3')
进行基于第二行和第三行的排序
其他网址:
<!DOCTYPE html>
<html>
<title>Sort a HTML List Alphabetically</title>
<body>
<p>Click the button to sort the list alphabetically:</p>
<button onclick="sortList('1')">Sort</button>
<div id="id01">
<ul class="group">
<li class="1">Aaron</li>
<li class="2">Tokyo</li>
<li class="3">2012</li>
</ul>
<ul class="group">
<li class="1">Jessica</li>
<li class="2">London</li>
<li class="3">2015</li>
</ul>
<ul class="group">
<li class="1">Peter</li>
<li class="2">New York</li>
<li class="3">2008</li>
</ul>
</div>
<script>
function sortList(sort_class_name) {
/*
sort_class_name - 1,2,3
*/
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.getElementsByClassName(sort_class_name);
console.log(b);
// 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.parentNode.insertBefore(b[i + 1].parentNode, b[i].parentNode);
switching = true;
}
}
}
</script>
</body>
</html>