当我创建一个页面时,我遇到了缓存问题。这是我的简化代码。
[HTML]
<body>
<div>here parent contents</div>
<input id="btn1" class="btn" data-val="1" type="button" />
<input id="btn2" class="btn" data-val="2" type="button" />
<input id="btn3" class="btn" data-val="3" type="button" />
<div id="childContents"></div>
</body>
[javascript]
$(".btn").click(function (e) {
$("#childContents").load("url?val=" + e.getAttribute("data-val"),
function () {
success call back function
});
});
重点是:
[子HTML]
<!-- the image change depanding on some condition -->
<div style="background-image: url('imgUrl')">
contents
</div>
每当我单击按钮并重新load
显示子视图时,我希望子视图所具有的图像会发生变化。但是由于缓存了图像,孩子的图像并没有改变。我该怎么办?
我想用javascript解决它,因为有时jquery版本会成为一个大问题,我总是考虑它的版本。所以我想让我的代码对 jQuery 的依赖很小。(例如,jquery 的异步 ajax 选项等不适用于低版本的 IE)
您可以将当前时间添加为缓存断路器。
$(".btn").click(function (e) {
$("#childContents").load("url?val=" + e.getAttribute("data-val"),
function () {
//get time since 1970 in milliseonds
var d = new Date();
var n = d.UTC();
//append a cache breaker
var imgUrl = "background.jpg" + "?t=" + n;
//set the img url
$('#backgrounddiv').css('background-image', 'url("'+imgUrl+'")');
});
});
<div id="backgrounddiv" style="background-image: url('background.jpg')">
contents
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句