3

我的网页有一个倒计时片段,它从隐藏字段中读取其剩余时间。它以 1 秒的步长从 300 倒数到 0,并因此更新隐藏字段。当我重新加载页面时,浏览器提供隐藏字段的旧值,而不是从服务器获取它。

片段是:

<span id="counter"> </span> <input type="hidden" id="remaining" value="300" />

我需要在事件侦听器块中获取页面的目标 URL,例如:

$(window).unload(function() {
alert(window.location.destination); });

当然,我弥补了“目的地”部分。我真正需要的是检测重新加载,并将哈希参数附加到 URL 以防止缓存。

4

1 回答 1

2

You can't get the URL of the page the user is going to in an unload function, or at all (in some cases it would be a privacy risk). And a fragment identifier (hash) on the URL will not prevent caching; changing it will not even reload the page. For a cachebuster you would have to write to the ?query part of the URL, which you could do through eg. location.search= '?'+Math.random();.

But none of that is a good idea. The behaviour where browsers ‘remember’ the previous value of a form when reloading or going back/forwards onto a page is unwanted, so your best bet is simply not to use a form field at all. Have the script write out data in another part of the DOM:

<span id="counter" class="remaining-300"></span>

and read that from the span element's .className in script, or simply write the variable straight to JS:

<span id="counter"></span>
<script type="text/javascript">
    var remaining= 300;
</script>

This will reset the countdown to 300 seconds each time the page is loaded.

You might also need to think about the ‘bfcache’, which on many modern browsers retains your original page — including all the content and script state in it — when a user navigates away, then brings it back without reloading when you press ‘Back’.

Currently that will continue ticking the countdown, but it won't have ticked whilst the page was being hidden, so you'll have as much time left as you had when you left. If that's not what you want, you could try setting a deadline timeout independently of the ticker interval, to always fire at the expected reload time. Or, as a last resort and generally to be avoided, you can break the bfcache deliberately by setting onunload to anything, even a function that does nothing.

于 2010-05-05T21:50:30.770 回答