jQuery 如何用jQuery刷新<img />的src?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1997901/
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
How to refresh the src of <img /> with jQuery?
提问by user198729
<img src="test.php" />
where test.php generates an image with a random number.
其中 test.php 生成一个带有随机数的图像。
Itried :
我试过 :
$('#verifyimage').click(function() {
$(this).attr('src',$(this).attr('src'));
});
But it doesn't work.
但它不起作用。
回答by K Prime
You can force a refresh by appending a random string at the end, thus changing the URL:
您可以通过在末尾附加一个随机字符串来强制刷新,从而更改 URL:
$('#verifyimage').click(function() {
$(this).attr('src', $(this).attr('src')+'?'+Math.random());
});
回答by Kobi
Add a timestamp or a random number:
添加时间戳或随机数:
var timestamp = new Date().getTime();
$(this).attr('src',$(this).attr('src') + '?' +timestamp );
回答by SeanDowney
Taking KPrimes great answer and adding in trackers suggestion, this is what I came up with:
采纳 KPrimes 很好的答案并添加跟踪器建议,这就是我想出的:
jQuery(function($) {
// we have both a image and a refresh image, used for captcha
$('#refresh,#captcha_img').click(function() {
src = $('#captcha_img').attr('src');
// check for existing ? and remove if found
queryPos = src.indexOf('?');
if(queryPos != -1) {
src = src.substring(0, queryPos);
}
$('#captcha_img').attr('src', src + '?' + Math.random());
return false;
});
});
回答by claws
In test.php set the headers of Content-Type:
to image/jpeg
在 test.php 中将标题设置Content-Type:
为image/jpeg