使用一些示例代码对a:中的列表进行排序:
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中的项目数量,以便我可以通过它们迭代来按图形排序我的数字?
答案 0 :(得分:3)
当你的javascript在加载html之前开始执行时会发生这种情况。如果是这种情况,那么您可能必须将调用包装在DomContentLoaded事件中的sortList()函数中,如下所示:
document.addEventListener("DOMContentLoaded", function(e) {
sortList();
});
答案 1 :(得分:0)
我同意Bala's answer,主要是因为我无法重现您的问题:
var div = document.getElementById('a');
var spans = div.getElementsByTagName('span');
console.log(spans.length);
&#13;
<div id="a">
<ul>
<li><span>hi</span></li>
<li><span>yo</span></li>
<li><span>dude</span></li>
</ul>
</div>
&#13;