试图在不会在同一用户会话中的每个不同页面视图上重新启动的网页上创建计数器。当前正在使用此代码(感谢Praveen Kumar Purushothaman),但是每次查看其他页面时,此计数器都会重置。
setTimeout(start, 0);
var i = 0;
var num = document.getElementById("number");
function start() {
increase();
setInterval(increase, 1000);
}
function increase() {
if (i < 100000) {
i += 10.41;
num.innerText = i.toFixed(2);
}
}
<span id="number"></span>
我的建议是将变量存储到会话存储中。我在评论中添加了更多详细信息:
setTimeout(start, 0);
// You're saving your current value here.
// Let's use localStorage. Set the i value if it doesn't exist for the first time.
if (!localStorage.getItem("i")) {
localStorage.setItem("i", 0);
}
var num = document.getElementById("number");
function start() {
increase();
setInterval(increase, 1000);
}
function increase() {
var i = localStorage.getItem("i");
if (i < 100000) {
i += 10.41;
// When you're making any changes, make changes to the localStorage too.
localStorage.setItem("i", i);
num.innerText = i.toFixed(2);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句