当列表项的数量未知时,如何在加载每个列表项后一一修改列表项
how to modify list items one by one as soon as each one is loaded, when number of list items is unknow
我不能使用 'windlow.onload' 或 'document.onload' 我也不知道列表项的数量,但我知道数量很大。我想在加载每个列表项后立即逐一修改列表项。我实现了以下代码,但我觉得可能有更好的解决方案。有什么想法吗?
function func_loopOverList(){
func_loopOverList.loadedCurr;//Current function call; number of loaded items
func_loopOverList.loadedLast;//Last function call; number of loaded items
if(document.readyState!=="complete"){
func_loopOverList.loadedCurr=document.getElementsByTagName("li").length;
for(var i = func_loopOverList.loadedLast; i < func_loopOverList.loadedCurr; i++){
var element=document.getElementsByTagName("li")[i];
//do things to element
}
func_loopOverList.loadedLast=func_loopOverList.loadedCurr;
setTimeout(func_loopOverList,15);
}else{
console.log("Happy End");
}
}
稍微修改了代码,将 getElementsByTagName 返回的动态 "node list" 更改为数组 - 只是为了不让事情变得混乱
function func_loopOverList() {
function process() {
var lis = document.getElementsByTagName("li");
func_loopOverList.loadedCurr = lis.length;
[].slice.call(lis, func_loopOverList.loadedLast || 0).forEach(function(element) {
//do things to element
});
func_loopOverList.loadedLast = func_loopOverList.loadedCurr;
}
process();
if (document.readyState !== "complete") {
setTimeout(func_loopOverList, 15);
} else {
process(); // one more time - this may be redundant, but it wont hurt
console.log("Happy End");
}
}
这里使用数组的forEach,只是因为,没有真正的原因,我更喜欢它。您可以使用 for 循环来完成它,但我只是觉得使用 getElementsByTagName 列表的 "copy" 更安全(因为它不是静态列表)
我不能使用 'windlow.onload' 或 'document.onload' 我也不知道列表项的数量,但我知道数量很大。我想在加载每个列表项后立即逐一修改列表项。我实现了以下代码,但我觉得可能有更好的解决方案。有什么想法吗?
function func_loopOverList(){
func_loopOverList.loadedCurr;//Current function call; number of loaded items
func_loopOverList.loadedLast;//Last function call; number of loaded items
if(document.readyState!=="complete"){
func_loopOverList.loadedCurr=document.getElementsByTagName("li").length;
for(var i = func_loopOverList.loadedLast; i < func_loopOverList.loadedCurr; i++){
var element=document.getElementsByTagName("li")[i];
//do things to element
}
func_loopOverList.loadedLast=func_loopOverList.loadedCurr;
setTimeout(func_loopOverList,15);
}else{
console.log("Happy End");
}
}
稍微修改了代码,将 getElementsByTagName 返回的动态 "node list" 更改为数组 - 只是为了不让事情变得混乱
function func_loopOverList() {
function process() {
var lis = document.getElementsByTagName("li");
func_loopOverList.loadedCurr = lis.length;
[].slice.call(lis, func_loopOverList.loadedLast || 0).forEach(function(element) {
//do things to element
});
func_loopOverList.loadedLast = func_loopOverList.loadedCurr;
}
process();
if (document.readyState !== "complete") {
setTimeout(func_loopOverList, 15);
} else {
process(); // one more time - this may be redundant, but it wont hurt
console.log("Happy End");
}
}
这里使用数组的forEach,只是因为,没有真正的原因,我更喜欢它。您可以使用 for 循环来完成它,但我只是觉得使用 getElementsByTagName 列表的 "copy" 更安全(因为它不是静态列表)