我正在构建一个页面来显示一堆网络摄像头图像并定期更新它们,以便该页面可用于一目了然的监控。但是,我在定期重新加载工作时遇到问题。我的代码看起来像:
<div class='cameras'>
<div class='camera'>
<h4>Desk</h4>
<img height='240' src='http://somehost/cameras/cam0/lastsnap.jpg' width='320'>
</div>
<div class='camera'>
<h4>Main Room</h4>
<img height='240' src='http://somehost/cameras/cam1/lastsnap.jpg' width='320'>
</div>
<div class='camera'>
<h4>Studio</h4>
<img height='240' src='http://somehost/cameras/cam2/lastsnap.jpg' width='320'>
</div>
</div>
理想情况下,我希望每隔几秒从指定的 URL 重新加载这些东西,而不必为每个相机生成单独的 JS。我已经将 jQuery 用于其他一些点点滴滴,所以坚持使用它会很棒 - 再一次,一个普通的 JS 解决方案也很好。
有什么想法吗,StackOverflow JS 大神们?
最佳答案
好的,解决了这个问题:
function refreshCameras() {
$('.camera img').attr('src', function(i, old) { return old.replace(/\?.+/,"?i=" + (Math.random()*1000)); });
setTimeout(refreshCameras, 1000);
}
function refreshCamerasFirst() {
$('.camera img').attr('src', function(i, old) { return old + "?i=" + (Math.random()*1000); });
setTimeout(refreshCameras, 1000);
}
$(function() {
setTimeout(refreshCamerasFirst, 1000);
});
将获取“camera”类中的所有 img 元素,并通过添加到 URL 的随机数通过缓存破坏每秒刷新它们,每次重新加载都会更改,而不会使用正则表达式替换 URL 太长现有号码。
关于javascript - 定期刷新页面上的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3898813/