![](/img/trans.png)
[英]How do I sort html list alphabetically using javascript on page load
[英]How do I alphabetically sort a list in HTML with jQuery?
我有 2 個 html 文件index.html
和list.html
。 當我將 list.html 加載到 index.html 時,我希望它自動按字母順序排序。
索引.html:
<button onclick="javascript:showlist()">Show</button>
<div id="content"></div>
列表.html:
<ul id="myUL">
<li>SUPERMAN</li>
<li>BATMAN</li>
<li>FLASH</li>
<li>ANARKY</li>
</ul>
js:
function showlist(){
$("#content").load("list.html");
sortList();
}
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("myUL");
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;
}
}
}
缺少的部分是onload handler 。 沒有它,您可能會在內容加載之前調用sortList()
。 否則你的功能有效
$("#content").load("list.html", function() {
console.log("Loaded");
sortList();
})
您無法在加載列表之前對其進行排序
你需要在你的 div 上使用事件負載
這樣編碼:
function showlist() {
$('#content').load('list.html');
}
const contentDiv = document.querySelector('#content')
contentDiv.onload =_=>
{
const
list = contentDiv.querySelector(`ul`)
, arrLI = [...list.querySelectorAll('li')]
.map(li=>({key:li.textContent.toLowerCase(),li}))
.sort((a,b)=>a.key.localeCompare(b.key))
arrLI.forEach(el=>list.appendChild(el.li) )
}
這是演示排序如何工作的代碼:
sortList('#content') function sortList( parentDiv ) { const list = document.querySelector(`${parentDiv} > ul`) , arrLI = [...list.querySelectorAll('li')] .map(li=>({key:li.textContent.toLowerCase(),li})) .sort((a,b)=>a.key.localeCompare(b.key)) arrLI.forEach(el=>list.appendChild(el.li) ) }
<div id="content"> <ul> <li>SUPERMAN</li> <li>BATMAN</li> <li>FLASH</li> <li>ANARKY</li> </ul> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.