我想让计数器在更新时保持动态且不可启动 网页, 这是我的代码问题是,当我刷新页面时,计数器(setTimeout)将再次从零计数到5我希望它从最后一个值开始计数 刷新
<html>
<head>
<meta charset="utf-8"/>
<title>Insert title here</title>
</head>
<script type="text/javascript">
setTimeout(function(){document.getElementById("tm").style.display='block'},
5000);
</script>
<body>
<form id="customer" action="/htmlvalidation" method="post">
<div>
<label>Time</label>
<input id="tm" type="text" style="display: none;"/>
</div>
<div>
<button type="submit">Add Customer</button>
</div>
</form>
</body>
</html>
谢谢
答案 0 :(得分:3)
您必须在客户端的浏览器中手动存储计数器值;默认情况下,浏览器在关闭(或刷新)时不会保留任何网页的状态。例如,您可以使用localStorage API:
const STORAGE_KEY = 'counter';
const TARGET_ELEMENT_ID = 'counter-div';
const INTERVAL = 1000;
const INC = 1;
// Notice the '+' below to make sure val is a number.
let val = +localStorage.getItem(STORAGE_KEY) || 0;
document.getElementById(TARGET_ELEMENT_ID).innerHTML = val;
setInterval(() => {
val += INC;
localStorage.setItem(STORAGE_KEY, val);
document.getElementById(TARGET_ELEMENT_ID).innerHTML = val;
}, INTERVAL);
Here is a working example on codepen(似乎stackoverflow的片段不支持localStorage)。
(我没有使用你的代码片段,因为我不确定你要做什么)。
答案 1 :(得分:1)
您可以在用户关闭或离开选项卡之前使用localStorage存储最后一次计时器迭代,并在需要时恢复。