我怎样才能让这段代码连续地循环遍历项目

How can I get this code to continuously loop through the items?

本文关键字:连续 代码 循环 项目 遍历 段代码      更新时间:2023-09-26

我有以下代码:

common_load_help("photo.xml");
function common_load_help(file)
{
  $(document).ready(function()
  {
    $.ajax(
    {
      type: "GET",
      url: SITE_URL + "/assets/help/" + file, //call this url
      dataType: 'xml',
      success: function(xml) //when we have the data...
      {
        var length = xml.getElementsByTagName("item").length;
        console.log("length: " + length);
        $('item', xml).each(function(i, el) //go through each help item
        {
          function looper()
          {
            $("#design-tips-content").html($(el, this).text());
          }
          setTimeout(looper, 5000);
        });
      }
    });
  });
}

我想要发生的是它把第一个元素放在design-tips-contentdiv中,然后等待5000秒,然后放第二个,然后放第三个,然后循环回到第一个元素。我该怎么做呢?现在看起来它只是显示最后一个元素。

注意:我试图为此创建一个jsfiddle (http://jsfiddle.net/allisonc/c8RLZ/),但我得到错误:MLHttpRequest cannot load http://www.asa.tframes.org:1881/assets/help/photo.xml. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

success函数中的代码应该可以工作。它的工作原理是构建一个条目文本数组,并将当前索引值存储在一个变量中。然后,它使用setInterval连续循环遍历所有项。

var tips = $('item', xml).get().map(function(item){
    return $(item).text();
});
var currentIndex = 0;
function looper() {
    if(currentIndex>=tips.length) {
        currentIndex = 0;
    }
    $('#design-tips-content').html(tips[currentIndex]);
    currentIndex++;
}
looper();
setInterval(looper, 5000);
工作小提琴