所以我的問題是有可能在強標記中按數字對列表項進行排序,當我嘗試使用下面的JavaScript代碼對數字進行排序並將它們從div標記中取出時。 (我使用這些JS代碼按名稱排序,它做工精細當b = ...(LI)) HTML:排序HTML ul
<section>
<button class="sortbynum" onclick="sortListNum()">Sort By Num</button>
<ul id="sort">
<li>
<div><h2>Name</h2></div>
<a href=""><img src=""/></a>
<div><span>Something:...</span></div>
<div><span>something:...</span></div>
<div><span>HHJS: <strong class="sortNum">456</strong></span></div>
</li>
<li>again</li>
</ul>
的JavaScript:
function sortListNum() {var list, i, switching, b, shouldSwitch, dir,switchcount = 0;list = document.getElementById("sort");switching = true;dir = "asc"; while (switching) {switching = false;b = list.getElementsByClassName("sortNum");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (dir == "asc") {
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
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;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}}}
您好,歡迎堆棧溢出,請花時間去通過[歡迎參觀](https://stackoverflow.com/tour)瞭解你在這裏的方式(並獲得你的第一張徽章),閱讀如何創建[最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve),並檢查[如何提出好問題](https://stackoverflow.com/help/how-to-ask),以便增加獲得反饋和有用答案的機會。 – DarkCygnus
祝你好運!附註,我們不是一個代碼寫作服務。請參考[如何提出一個好問題?](https://stackoverflow.com/help/how-to-ask)。你有沒有試過做任何研究?你有什麼嘗試?這裏的問題應該有一個明確的問題/問題,顯示的研究和[最小,完整和可驗證](https://stackoverflow.com/help/mcve)示例。 – GrumpyCrouton
你有問題標記爲jQuery,所以看看:https://stackoverflow.com/questions/304396/what-is-the-easiest-way-to-order-a-ul-ol-in-jquery 。我會將類添加到您想要排序的每個位,然後排序函數可以輕鬆地將目標定位到li –