无法将我的计时器值存储在 cookie 中
Can't store my timer values in a cookie
我昨天询问了在浏览器关闭时保存计时器值,然后在用户打开它时再次开始计数的问题。我发现使用 cookie 一定是一个很好的解决方案,所以我添加了 set 和 getcookie 函数,但我仍然无法获取计时器值。这可能很容易,但我看不出出了什么问题,因为我在javascript中仍然太菜鸟了。有人知道我做错了什么吗?谢谢!!这是我到目前为止的代码:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>Test</title>
<script type="text/javascript">
var sec = 0;
var min = 0;
var hr = 0;
var dias = 0;
var bool = true;
function stopwatch() {
sec++;
if (sec == 60) {
sec = 0;
min += 1;
}
if (min == 60) {
min = 0;
hr += 1;
}
if (hr == 24) {
hr = 0;
dias += 1;
}
totalTime = ((dias<=9) ? "0" + dias : dias) + "d, " + ((hr<=9) ? "0" + hr : hr) + " : " + ((min<=9) ? "0" + min : min) + " : " + ((sec<=9) ? "0" + sec : sec);
document.getElementById("timer").innerHTML = totalTime;
if (bool == true) {
start = setTimeout("stopwatch()", 1000);
}
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie (name) {
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
</script>
</head>
<body onload="stopwatch()">
<div id="timer" name="timer"> </div>
<button onclick="bool = false"; > pause </button>
<button onclick="bool = true;stopwatch();" > resume </button>
<form>
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie',timer.value, exp)">
</form>
<form>
<input type="button" value="Get Cookie Value" onClick="this.form.tf.value = getCookie('myCookie')">
<input type="text" name="tf" size="30">
</form>
</body>
</html>
正如@floorish所说,timer.value
不存在,timer
因为它是一个 DIV 元素并且没有value
属性。
因此,您需要将timer.value
更改为document.getElementById('timer').innerHTML
就可以了。
现场jsFiddle演示
编辑 1:
如果您希望计时器开始计算它在 cookie 上的保存位置,您应该在加载页面时读取 cookie。我做了这样:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
</head>
<body>
<div id="timer"> </div>
<button id="switcher"></button>
<p><input type="button" id="setCookie" value="Set a Cookie"></p>
<p><input type="button" id="getCookie" value="Get Cookie Value"> <input type="text" id="lastTime" size="30"></p>
<script>
/**
* Set cookie
* @param {string} name Name of cookie
* @param {string} value Value of the cookie
* @param {object} expires Date object of expire time
*/
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
/**
* Get cookie
* @param {string} name Name of cookie
* @return {?string}
*/
function getCookie(name) {
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var time;
/**
* Format time and return formatted string
* @param {number} time Time in seconds that will formatted
* @return {string}
*/
function formatTime(time) {
var days = parseInt(time / 86400, 10); // Calculate days from seconds and delete decimals.
if (0 > days) {
days = 0;
}
var hours = parseInt((time - days * 86400) / 3600, 10); // Calculate hours from seconds and delete decimals.
if (0 > hours) {
hours = 0;
}
var mins = parseInt((time - days * 86400 - hours * 3600) / 60, 10); // Calculate minutes from seconds and delete decimals.
if (0 > mins) {
mins = 0;
}
var seconds = parseInt(time - days * 86400 - hours * 3600 - mins * 60, 10); // Calculate remain seconds.
// Array for the time display, the content is something like:
// array(3) {
// 0: '01',
// 1: '57',
// 2: '31'
// }
var displayHours = [
((hours <= 9) ? '0' + hours : hours),
((mins <= 9) ? '0' + mins : mins),
((seconds <= 9) ? '0' + seconds : seconds)
];
// Return formatted days and the displayHours is joined with ' : ', then it like this:
// '00d, ' + '01 : 57 : 31'
return ((days <= 9) ? '0' + days : days) + 'd, ' + displayHours.join(' : ');
}
/**
* Append to the 'timer' DIV the formatted time
*/
function watch() {
// Append to the 'timer' DIV a formatted time
// ++time equal time = time + 1
document.getElementById('timer').innerHTML = formatTime(++time);
}
/**
* @type {?object} Variable to handle the interval timer.
*/
var timer = null;
/**
* Switch between 'pause' and 'resume' time
*/
var switcher = function () {
if (timer) { // If timer is assigned and not null
clearInterval(timer); // Clear the interval to stop
timer = null; // Null the timer
document.getElementById('switcher').innerHTML = 'Resume'; // Change the word of the button to 'Resume'.
} else {
timer = setInterval(watch, 1000); // Start the interval timer
document.getElementById('switcher').innerHTML = 'Pause'; // Change the word of the button to 'Pause'.
}
};
// Assign on click event to 'switcher' button
document.getElementById('switcher').onclick = switcher;
// Assign on click event to 'setCookie' button
document.getElementById('setCookie').onclick = function () {
// New Date object for the expire time
var exp = new Date();
// Set the expire time
exp.setTime(exp + 2592000000);
// Set a 'time' cookie with the current timer time and expire time object.
setCookie('time', time, exp);
};
// Asign on click event to 'getCookie' button
document.getElementById('getCookie').onclick = function () {
document.getElementById('lastTime').value = formatTime(getCookie('time'));
};
// Function that will call when document loaded.
window.onload = function () {
// Get the time saved into the cookie and turn it to number.
var oldTime = parseInt(getCookie('time'), 10);
if (0 < oldTime) { // If the time saved
time = oldTime; // Set the current time to the saved time
} else { // If not time saved
time = 0; // Set the current time to zero.
}
// Start the timer
switcher();
}
</script>
</body>
</html>
现场jsFiddle演示
cookie 值被保存为"未定义",因为您没有存储正确的值:timer.value
将其更改为totalTime
,它就可以工作:
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie',totalTime, exp)">
看到这个小提琴
相关文章:
- 用于存储、检索和附加到url的javascript cookie
- 为什么大型网站不;I don’我更喜欢本地存储而不是cookie
- 将会话登录页存储在cookie中以进行表单解析(通过隐藏字段)
- 使用 Cookie 存储数据
- 如何将jQuery克隆的文本输入保存到cookie或html5存储中
- Javascript Security:将敏感数据存储在比cookie更安全的自调用函数中
- 为样式表切换器存储js cookie
- 使用纯js在cookie中存储多个值
- 如何在Javascript的跨域操作中存储cookie
- 通过javascript存储cookie
- 使用滑动存储cookie以删除jquery mobile
- 在用户浏览表单时存储cookie
- 在服务器上存储 Cookie 数据
- 如何在 socket.io 中存储cookie(socket.handshake.headers.cookie)
- 函数获胜't存储cookie
- 当你在iOS的主屏幕上添加一个web应用程序时,你就不能再存储cookie了
- 使用ETag在浏览器中存储cookie信息
- Phonegap/Javascript应用程序:我如何存储cookie
- 本地存储cookie会回退
- Javascript Cookie代码未存储Cookie/读取空Cookie值