循环遍历DIV id数组,并每隔x秒刷新这些DIVS


Loop through array of DIV ids, and refresh those DIVS every x seconds

假设我有4个div:

<div id='blue'></div>
<div id='refresh12'></div>
<div id='red'></div>
<div id='refresh23'></div>

我将页面上以"刷新"开头的每个div放入一个数组中,如下所示:

var divs = $('div[id^="refresh"]');

现在,我想做的是每5秒刷新一次数组中的div。我知道我需要使用SetInterval,但我不确定如何开始循环。此外,div并不是从另一个页面提取内容,而是从同一个页面,只是需要每5秒刷新一次的动态数据。感谢您的帮助。谢谢

使用setInterval并不总是最好的主意,因为如果您的操作需要很长时间并且处于阻塞状态,那么调用可能会堆积起来。

你可以像这样使用setTimeout()调用来实现你想要的:

var divs = $('div[id^="refresh"]');
setTimeout(function refreshThem () {
    //code to refresh your divs
    divs.xy();
    setTimeout(refreshThem, 5000);
}, 5000);

或者如果您希望第一次刷新同时运行:

(function refreshThem () {
    //code to refresh your divs
    divs.xy();
    setTimeout(refreshThem, 5000);
})();

基本上,当刷新完成时,会设置一个新的超时,以便在5秒内再次运行相同的代码。

尝试以下操作:

setInterval(function() {
$('div[id^="refresh"]').each(function(inx) {
// update each div here
});
},5000);

您需要做的是类似的操作

setInterval(function(){
    $('div[id^="refresh"]').each(function(i,el){
        $(el).load('pageURL ' + $(el).prop('id'));
    })
}, 500)

或者如某人所言,setTimeout()

$(function(){   
     var int=self.setInterval(RefreshDivs,5000);     
});
function RefreshDivs(){
 // do your code to update/ refresh the div content. May be ajax call..
}