2017-07-05 23 views
0

所以我的問題是有可能在強標記中按數字對列表項進行排序,當我嘗試使用下面的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; 
    } 
}}} 
+0

您好,歡迎堆棧溢出,請花時間去通過[歡迎參觀](https://stackoverflow.com/tour)瞭解你在這裏的方式(並獲得你的第一張徽章),閱讀如何創建[最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve),並檢查[如何提出好問題](https://stackoverflow.com/help/how-to-ask),以便增加獲得反饋和有用答案的機會。 – DarkCygnus

+0

祝你好運!附註,我們不是一個代碼寫作服務。請參考[如何提出一個好問題?](https://stackoverflow.com/help/how-to-ask)。你有沒有試過做任何研究?你有什麼嘗試?這裏的問題應該有一個明確的問題/問題,顯示的研究和[最小,完整和可驗證](https://stackoverflow.com/help/mcve)示例。 – GrumpyCrouton

+0

你有問題標記爲jQuery,所以看看:https://stackoverflow.com/questions/304396/what-is-the-easiest-way-to-order-a-ul-ol-in-jquery 。我會將類添加到您想要排序的每個位,然後排序函數可以輕鬆地將目標定位到li –

回答

0

我我設法從中推斷出你是否可以從內聯元素中提取文本。

你可以像其他任何東西一樣選擇它們,但它更有趣一點。

innerHTML返回HTML,其可以是HTML或純文本或兩者。

innerText返回純文本。

textContent返回所有包含的純文本連接成一個字符串,當下一個元素位於新行時,僅由換行符分隔。

既然你已經不僅僅是元素中的數量更多的文本,只需選擇strong標籤,並呼籲innerText

document.querySelector('#sort .sortNum').innerText 
+0

中我不需要提取文本,我需要按強號中的數字對這些列表項進行排序。 – theKln