使用javascript在图像url后添加随机变量 [英] Add random variable after image url with javascript
问题描述
我有一个页面,上面有一张图片,但是这张图片经常变化,但它有相同的 URL.为了绕过浏览器缓存旧版本的图像,我想在 URL 后添加一个随机数变量.使用 Javascript 执行此操作的最佳方法是什么?
I have a page with an image on it, however this image changes quite frequently, but it has the same URL. To bypass the browser from caching an older version of the image, I want to add a random number variable after the URL. What is the best way to do this with Javascript?
所以当页面加载时,它不会加载:
So when the page loads, it does not load:
http://test.com/image.png
而是加载:
http://test.com/image.png?43673890
因此每次重新加载页面时,它都会有一个新变量,因此可以看到最新版本的图像.
So each time the page is reloads, it has a new variable so the latest version of the image is visible.
推荐答案
给你的img标签一个id,然后你就可以了
Give your img tag an id, then you can
document.getElementById("imageid").src=document.getElementById("imageid").src + "?" + Math.random()* 100000000000000000000;
如果初始 url 有 ?然后做
if the initial url has ? then do
document.getElementById("imageid").src=document.getElementById("imageid").src.split('?')[0] + "?" + Math.random()* 100000000000000000000;
这篇关于使用javascript在图像url后添加随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!