我试图将三个不同的 html 文件加载到一个 div 中,一个接一个,延迟 5 秒。在它循环通过所有三个之后,我希望它继续重复。我尝试使用超时来执行此操作但它仍然无法正常工作。任何帮助将不胜感激.. 下面的代码片段
<script type="text/javascript">
$(document).ready(function() {
jQuery(window).load (function timeout() {
setTimeout(function () {
if($("#news_sections").hasClass("news1")){
$("#news_sections").attr('class', "news2");
$( "#news_sections" ).load( "section2.html" );
}else if($("#news_sections").hasClass("news2")){
$("#news_sections").attr('class', 'news3');
$( "#news_sections" ).load( "section3.html" );
}else{
$("#news_sections").attr('class', 'news1');
$( "#news_sections" ).load( "section1.html" );
};
timeout();
}, 4000);
});
});
});
</script>
最佳答案
未经测试,但你应该这样做:
$(function(){
var curIdx = 0, /* internal counter */
urls = ['page1.html','page2.html','page3.html'], /* your urls*/
doCache = true, /* set to false to disable caching */
cache = {} /* storage */;
function nextPage(){
var data = false,
url = urls[curIdx];
if(doCache && cache[url]) {
data = cache[url];
}
curIdx += 1;
// all urls displayed - reset counter, show first page again
if(curIdx == urls.length) {
curIdx = 0;
}
// load data (and cache it, if doCached option is true)
if(!data){
$("#content").load(url, function(data){
cache[url] = data;
nextTimer();
})
} else {
$("#content").html(data);
nextTimer();
}
};
// now to timeout
function nextTimer(){
window.setTimeout(function(){ nextPage() }, 5000); // 5 Seconds
}
// and run it...
nextPage();
});
请注意,这可能不适用于外部 URL。
关于javascript - 不同的页面延迟加载到 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535452/