问题描述
我有以下代码:
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-content div 中,然后等待 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.
注意:我试图为此创建一个 jsfiddle (http://jsfiddle.net/allisonc/c8RLZ/) 但我收到错误消息:MLHttpRequest 无法加载 http://www.asa.tframes.org:1881/assets/help/photo.xml.请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源http://fiddle.jshell.net".
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.
推荐答案
success 函数中的这段代码应该可以工作.它的工作原理是构建项目文本的数组,并将当前索引值存储在变量中.然后,它使用 setInterval
不断循环遍历所有项目.
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);
这篇关于我怎样才能让这个代码连续循环遍历这些项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!