假设我有 4 个 div:
<div id='blue'></div>
<div id='refresh12'></div>
<div id='red'></div>
<div id='refresh23'></div>
我将我页面上以“refresh”开头的每个 div 放入这样的数组中:
var divs = $('div[id^="refresh"]');
现在,我想要做的是每 5 秒刷新一次数组中的 div。我知道我需要使用 SetInterval,但我不确定如何启动循环。此外,div 不是从另一个页面中提取内容,而是从同一页面中提取内容,只是需要每 5 秒刷新一次的动态数据。任何帮助表示赞赏。谢谢。
最佳答案
使用 setInterval
是 not always the best idea ,因为如果您的操作耗时很长并且处于阻塞状态,调用可能会堆积起来。
您可以使用 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 秒内再次运行相同的代码。
关于php - 遍历 DIV id 数组,每 x 秒刷新一次这些 DIVS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622392/