I cannot use 'windlow.onload' or 'document.onload' also I don't know the number of list items, but I know the number is large. I want to modify list items one by one as soon as each one is loaded. I implemented the following code, but I feel like there might be a better solution. Any idea?
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");
}
}
Slightly modified the code, change the dynamic "node list" returned by getElementsByTagName to an array - just so things don't get racey
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");
}
}
This uses array's forEach, just because, no real reason, I prefer it. You can do it with a for loop, but I just get the feeling that it's safer to work with a "copy" of the getElementsByTagName list (because it isn't a static list)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.