带有id的Div存在但jQuery无法识别

时间:2015-05-20 14:16:12

标签: javascript jquery setinterval

我有一个页面,每5秒钟将另一个加载到div中。 我使用jQuery将它加载到document.ready上,但是当调用setInterval函数时,它不会每5秒重新加载一次。  我收到错误 "Cannot read property 'load' of null"

<div id="wallboard"></div>

<script type="text/javascript">     
    $(document).ready(function(){
     //Put in initial data THIS WORKS
     $('#wallboard').load('refresh_wall2_test.php'); 

        //Refresh wallboard div every 5 seconds THIS DOESN'T WORK
        $(function(){ 
            window.setInterval(
            function(){                     
                $('#wallboard').load('refresh_wall2_test.php'); 
            } ,5000);
        });
    });
</script>

4 个答案:

答案 0 :(得分:1)

$(function(){ 
    $('#wallboard').load('refresh_wall2_test.php'); 
    window.setInterval(
        function(){                     
            $('#wallboard').load('refresh_wall2_test.php'); 
        } ,5000);
    });
})();

答案 1 :(得分:1)

在document.ready之外定义函数并在那里调用setInterval。

class MyTestCase(unittest.TestCase):
    def run(self, result=None):
        '''Show log output on failed tests'''

        if result:
            orig_err_fail = result.errors + result.failures

        super().run(result)

        if result and result.errors + result.failures > orig_err_fail:
            print ("assertion failed")

答案 2 :(得分:1)

这对我来说很有效。我把你的setInterval函数放在一个变量上,所以如果需要,你可以clearInterval

&#13;
&#13;
$(document).ready(function () {
        "use strict";
        
        // Load the window on ready...
        $('#wallboard').load('home.php');

        //Refresh wallboard div every 5
        window.reloadDiv = window.setInterval(
            function () {
                $('#wallboard').load('refresh_wall2_test.php');
        }, 5000);
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wallboard"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您首先不需要setInterval。您需要做的就是等待第一个加载完成,在完整的回调中,执行一个setTimeout,它会以设置的延迟重新加载div。希望有所帮助。

$(document).ready(function() {
    //Store the reference
    var $elem = $('#wallboard');
    //Create a named self executing function
    (function loadPage() {
        $elem.load('refresh_wall2_test.php', function() {
            //When the request is complete, do a timeout which calls the function again.
            window.setTimeout(function() {
                loadPage();
            }, 5000);
        });
    }());
});