问题
I have the following code:
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);
});
}
});
});
}
What I would like to happen is it puts the 1st element in the design-tips-content div, then wait 5000 seconds, then put the 2nd, then put the 3rd, then loop back to the first element. How would I go about doing that? Right now it just seems like it is just showing the last element.
Note: I tried to create a jsfiddle for this (http://jsfiddle.net/allisonc/c8RLZ/) but I get the error: 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.
回答1:
This code inside the success function should work. It works by building an array of the items' text, and storing the current index value in a variable. Then, it uses setInterval
to continually loop through all the items.
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
来源:https://stackoverflow.com/questions/24781387/how-can-i-get-this-code-to-continuously-loop-through-the-items