我是javascript的新手,我想用localStorage创建一个倒数计时器,它从给定的时间开始,到00:00:00结束,但它不起作用, 当我运行我的代码时,它显示的值为“1506”。
这是我的代码
program
答案 0 :(得分:2)
Hour, Minute, Second, CurrentTime
块旁边声明变量if else
。在这种情况下,它们不在function CountDown()
范围内。 CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
localStorage.setItem("counter", CurrentTime);
醇>
var Hour = 3;
var Minute = 25;
var Second = 60;
var CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
function CountDown() {
document.getElementById('lblDuration').innerHTML = CurrentTime;
Second--;
if (Second == -1) {
Second = 59;
Minute--;
}
if (Minute == -1) {
Minute = 59;
Hour--;
}
CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
}
setInterval(function () {
CountDown();
}, 1000);

<div id="lblDuration"></div>
&#13;
答案 1 :(得分:1)
当localStorage可用时,您不需要设置小时,分钟和秒的值。因此,当执行倒计时功能时,它会发现Second未定义,而语句Second--将Second转换为NaN。 要修复它,只需初始化小时,分钟和第二个变量。 我已经重构了你的代码,希望它有所帮助:
function CountDown() {
var currentTime = getCurrentTime();
printCurrentTime(currentTime)
currentTime.second--;
if (currentTime.second == -1) {
currentTime.second = 59;
currentTime.minute--;
}
if (currentTime.minute == -1) {
currentTime.minute = 59;
currentTime.hour--;
}
setCurrentTime(currentTime);
}
function setCurrentTime(newCurrentTime){
if(localStorage) localStorage.setItem("counter", JSON.stringify(newCurrentTime));
else setCurrentTime.storage = newCurrentTime;
}
function getCurrentTime(){
var result = localStorage ? localStorage.getItem("counter") : setCurrentTime.storage;
result = result || {hour:3, minute:25, second:60};
if (typeof(result) === "string")result = JSON.parse(result);
result.toString = function(){
return result.hour + ":" + result.minute + ":" + result.second;
}
return result;
}
function printCurrentTime(currentime){
var domTag = document.getElementById('lblDuration');
if(domTag) domTag.innerHTML = currentime.toString();
else console.log(currentime);
}
setInterval(function () { CountDown(); }, 1000);