我制作了排序腳本(A到Z)
我的問題是我需要添加什么才能具有 unsort 功能,我的意思是設定為默認值(在對它們進行排序之前是怎樣的)。
代碼:
function sortList() {
document.getElementById('sortedtxt').innerHTML = 'Sorted A-Z';
document.getElementById('sortedtitle').innerHTML = 'BFMAS - Sorted A-Z';
var list, i, switching, b, shouldSwitch;
list = document.getElementById("sortingUL");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("LI");
for (i = 0; i < (b.length - 1); i ) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() > b[i 1].innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i 1], b[i]);
switching = true;
}
}
}
uj5u.com熱心網友回復:
請使用此代碼 JS & HTML
let globalList, temp = [], sorted = true; document.getElementById("sort").addEventListener('click', sortList); document.getElementById("unsorted").addEventListener('click', UnsortedList); function UnsortedList() { let currentList = document.getElementById("countries"); currentList.innerHTML = ''; temp.forEach(function (item) { let li = document.createElement('li'); currentList.appendChild(li); li.innerHTML = item; }); sorted = true; } function getTempArray(pList) { globalList = pList.getElementsByTagName("li"); temp = []; for (let j = 0; j < globalList.length; j ) { temp.push(globalList[j].innerText); } } function sortList() { let list, i, switching, b, shouldSwitch; list = document.getElementById("countries"); if (sorted === true) { getTempArray(list); sorted = false; } switching = true; while (switching) { switching = false; b = list.getElementsByTagName("li"); for (i = 0; i < (b.length - 1); i ) { shouldSwitch = false; if (b[i].innerHTML.toLowerCase() > b[i 1].innerHTML.toLowerCase()) { shouldSwitch = true; break; } } if (shouldSwitch) { b[i].parentNode.insertBefore(b[i 1], b[i]); switching = true; } } }<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Pues </title> </head> <body> <p>Click the button to sort the list alphabetically ??</p> <button id="sort"><b>Sort</b></button> <button id="unsorted"><i>Unsorted</i></button> <ul id="countries"> <li>Peru</li> <li>Argentina</li> <li>Brazil</li> <li>Colombia</li> <li>Paraguay</li> <li>Bolivia</li> </ul> </body> </html>
uj5u.com熱心網友回復:
首先,您在原位(就地)對 DOM 元素進行排序,而不是擁有單獨的串列資料結構(例如陣列)并將 DOM 視為視圖,這似乎有點瘋狂……即將串列資料呈現到 DOM 中根據需要(即更新后或排序后)。
推薦:
- 將
sortedtxt資料移動到陣列中。 - 保留原始排序順序的陣列副本。
- 創建并呼叫一個函式,將陣列元素呈現到 DOM 中,例如到適當的
<ul>,<ol>或 中<table>。 - 在更改排序順序或恢復原始順序的用戶操作上,將其應用于陣列,然后再次呼叫上述函式。
好處:
- 更好的網頁性能。
- 更清晰、更簡單,將資料與表示代碼分開。
- 您可以更輕松地實作更高級的排序功能,例如按字串屬性值對物件陣列進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376151.html
標籤:javascript 列表 功能 排序
