javascript 定期刷新 jQuery 中的 <img>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7337113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refresh <img> in jQuery periodically
提问by joedborg
Similar to How to reload/refresh an element(image) in jQuerybut not at the same time.
类似于如何在 jQuery 中重新加载/刷新元素(图像)但不是同时。
I have a webcam that saves images every 2 seconds rather than streaming. Using jQuery (or straight JS) I want to refresh just the image element.
我有一个网络摄像头,它每 2 秒保存一次图像而不是流式传输。使用 jQuery(或直接 JS)我只想刷新图像元素。
Should be easy, but all my searches show the refresh on request.
应该很容易,但我所有的搜索都会根据要求显示刷新。
回答by Andy
setInterval(function(){
$("#myimg").attr("src", "/myimg.jpg?"+new Date().getTime());
},2000);
回答by Simone Gianni
You must force the browser to realod the image instead of taking it from cache. You can do it by changing the url, adding a useless parameter that changes each time, for example a timestamp.
您必须强制浏览器重新显示图像而不是从缓存中获取它。您可以通过更改 url、添加每次更改的无用参数(例如时间戳)来实现。
$('img.webcam').each(function() {
var jqt = $(this);
var src = jqt.attr('src');
src = src.substr(0,src.indexOf('?'));
src += '?_ts=' + new Date().getTime();
jqt.attr('src',src);
});
Execute this snippet inside a timer or on a click or both or whatever.
在计时器内或单击时执行此代码段,或两者兼而有之。
回答by Joe
setIntervalis a timer that will execute a function everything x milliseconds
setInterval是一个计时器,它将在 x 毫秒内执行一个函数
setInterval(function () {
var d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
}, 2000);
回答by Niko
This should do the job:
这应该可以完成这项工作:
window.setInterval(function() {
var d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
}, 2000);
回答by ShankarSangoli
Add a timestamp to the image source it will refresh.
向将刷新的图像源添加时间戳。
setInterval(function(){
$("img").each(function(){
var timeStamp = (new Date()).getTime();
$(this).attr("src", $(this).attr("src") + timeStamp );
});
}, 2000);