How to refresh the src of <img /> with jQuery?
<img src="test.php" />
where test.php generates an image with a random number.
Itried :
$('#verifyimage').click(function() {
$(this).attr(开发者_如何学编程'src',$(this).attr('src'));
});
But it doesn't work.
You can force a refresh by appending a random string at the end, thus changing the URL:
$('#verifyimage').click(function() {
$(this).attr('src', $(this).attr('src')+'?'+Math.random());
});
Add a timestamp or a random number:
var timestamp = new Date().getTime();
$(this).attr('src',$(this).attr('src') + '?' +timestamp );
Taking KPrimes great answer and adding in trackers suggestion, this is what I came up with:
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;
});
});
In test.php set the headers of Content-Type:
to image/jpeg
精彩评论