jquery - 循环遍历链接数组并在设定的时间间隔后动态加载每个链接的内容

标签 jquery ajax arrays loops get

使用 jQuery,我想循环遍历链接数组,并在设定的时间间隔后将每个链接的内容加载到 DIV 中。例如,如果我有我的父页面“parent.html”和一个链接数组 - “test1.html、test2.html 和 test3.html”,我想首先将 test1.html 加载到 Parent.html 中的 div 中,然后然后在设定的时间间隔后用 test2.html 替换 test1.html,然后用 test3.html 无限期地重复该过程。

如果有人能帮助我,我将非常感激。我尝试过使用 .get() 和 setTimeout() 但只是没有专业知识和经验将这一切放在一起。非常欢迎任何帮助。

谢谢。

最佳答案

这将实现你想要的。

You can view a working demo here.它只加载每个链接一次,然后缓存结果。后续迭代只需从缓存中提取即可。

$(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

<ul id="links">
  <li><a href="test1.html">Test 1</a></li>
  <li><a href="test2.html">Test 2</a></li>
  <li><a href="test3.html">Test 3</a></li>
</ul>
<div id="content">

</div>

关于jquery - 循环遍历链接数组并在设定的时间间隔后动态加载每个链接的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2046352/

相关文章:

javascript - 在 Rails 中重新加载页面后,某些功能无法运行

javascript - Jquery - .append 之后,.hover 在其他元素上不起作用

javascript - 使用 AJAX 将数据发送到 PHP

arrays - 如何在 Scala 中进行装箱?

javascript - 如何选中和取消选中 div 内的所有复选框

javascript - jquery过滤器后面板主体文本区域消失

javascript - 如何使用jquery关闭自动完成/建议框

jquery - ajax回调后更改内部文本不起作用?

java - 循环遍历字符串来检查值。 (Java计算器)

javascript - 如何将转换后的字符串转换回数组?