javascript - 不同的页面延迟加载到 div 中

标签 javascript jquery html css

我试图将三个不同的 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/

相关文章:

javascript - 防止在 Kendo 编辑器中删除不必要的空格

javascript - jQuery javascript 按键功能不适用于 IE8

javascript - 发送 POST 请求 - angular4

javascript - 确定从 jQuery/JavaScript 中单击了哪个提交按钮

javascript - 如何在特定条件下将数组分成 3 个对象

php - 在同一个项目中结合 Eclipse PDT 和 Aptanta 插件 w/JQuery

javascript - 在 jQuery 中序列化为 JSON

html - 我是否误解了填充如何与内联 block 元素和 ul 元素一起使用?

javascript - 显示 Jasper Reports Server 提供的 pdf

javascript - 从原型(prototype)继承属性