2014-07-16 46 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