要使用JavaScript对HTML列表进行排序,代码如下-
<!DOCTYPE html> <html> <body> <h1>Sorting list example</h1> <button>Click to sort</button> <ul class="animalList"> <li>Giraffe</li> <li>Camel</li> <li>Dog</li> <li>Lion</li> <li>Cheetah</li> <li>Cat</li> </ul> <script> document .getElementsByTagName("button")[0] .addEventListener("click", sortList); function sortList() { var list, i, sortFlag, LiEle, sorted; list = document.querySelector(".animalList"); sortFlag = true; while (sortFlag) { sortFlag = false; LiEle = list.getElementsByTagName("LI"); for (i = 0; i < LiEle.length - 1; i++) { sorted = false; if ( LiEle[i].innerHTML.toLowerCase() > LiEle[i + 1].innerHTML.toLowerCase() ) { sorted = true; break; } } if (sorted) { LiEle[i].parentNode.insertBefore(LiEle[i + 1], LiEle[i]); sortFlag = true; } } } </script> </body> </html>
输出结果
上面的代码将产生以下输出-
在点击“点击排序”按钮-