2014-07-16 43 views
0

我有以下代码:我怎样才能得到这个代码连续循环的项目?

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); 
     }); 

     } 
    }); 
    }); 
} 

我想什么发生的是它把第1个要素的设计提示内容DIV,然后等待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.

+0

[本小提琴](http://jsfiddle.net/c8RLZ/1/)应该修正错误。 – parchment

回答

0

成功函数内部此代码应工作。它通过构建项目的文本数组并将当前索引值存储在变量中起作用。然后,它使用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); 

Working fiddle

+0

谢谢你的工作。你有什么想法,我会如何添加幻灯片数字? – AllisonC

+0

@AllisonC你可以使用'currentIndex + 1'。 – parchment