使用一些示例代码对中的列表进行排序:
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中的项数,这样我就可以遍历它们,按照字幕对我的图形进行排序?

发布于 2017-07-28 12:50:20
当您的javascript在html加载之前开始执行时,就会发生这种情况。如果是这种情况,则可能必须将对sortList()函数的调用包装在DomContentLoaded事件中,如下所示:
document.addEventListener("DOMContentLoaded", function(e) {
sortList();
});发布于 2017-07-28 12:52:11
我同意Bala's answer的观点,主要是因为我无法重现您的问题:
var div = document.getElementById('a');
var spans = div.getElementsByTagName('span');
console.log(spans.length);<div id="a">
<ul>
<li><span>hi</span></li>
<li><span>yo</span></li>
<li><span>dude</span></li>
</ul>
</div>
https://stackoverflow.com/questions/45365027
复制相似问题