通過一些示例代碼工作進行排序內的列表:如何獲得的getElementsByTagName的長度與JavaScript
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("timelineul");
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("figcaption");
//Loop through all list items:
console.log(b);
console.log(b.length);
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:*/
console.log(b[i].innerHTML);
console.log(b[i+1].innerHTML);
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;
}
}
}
的console.log(B);產生這樣的:
但是, 的console.log(b.length個);結果爲0
如何獲取b中的項目數量,以便我可以遍歷它們以按照圖形對我的數字進行排序?
'的document.getElementById( 「timelineul」)。length' ?? – marekful
@marekful認真嗎? – undefined
我想知道如果問題可能是由於'getElementsByTagName()'返回一個**活的NodeList **,你正在操縱,但它是早上6點和我睡覺(yup)的時間。嘗試使用'querySelector()'來獲取列表。 –