当列表项的数量未知时,如何在加载每个列表项后立即逐个修改列表项

how to modify list items one by one as soon as each one is loaded, when number of list items is unknow

本文关键字:列表 加载 修改 未知      更新时间:2023-09-26

我不能使用'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返回的动态"节点列表"更改为数组 - 这样事情就不会变得激烈

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列表的"副本"更安全(因为它不是静态列表)