Loop through an Array of links and dynamically load the contents of each after a set interval

后端 未结 4 1332
孤城傲影
孤城傲影 2021-01-16 06:47

Using jQuery I would like to loop through an array of links and load the contents of each link into a DIV after a set interval. For example, if I have my parent page \"paren

4条回答
  •  遥遥无期
    2021-01-16 07:14

    This will do what you want.

    You can view a working demo here. It only loads each link once, then caches the result. Subsequent iterations simply pull from the cache.

    $(function(){
       var curIdx = 0,
           urls   = $.map($("#links a"),function(el){ return $(el).attr('href') }),
           cache  = {};
    
       function nextPage(){
           var url  = urls[curIdx],
               data = cache[url];
    
           curIdx += 1; if(curIdx == urls.length) curIdx = 0;
    
           if(!data){
             $("#content").load(url, function(data){
               cache[url] = data;
               nextTimer();
             })
           } else {
             $("#content").html(data);
             nextTimer();
           }
       };
    
       function nextTimer(){
         window.setTimeout(function(){ nextPage() }, 3000); // 3 Seconds
       }
    
       nextPage();
    });
    

    HTML

    
    

提交回复
热议问题