<script type="text/javascript">
$(function () {
'use strict';
var course = 'Learn JavaScript';
alert(course); // 弹出 'Learn JavaScript'
alert(window.course); // 为什么弹出的是 undefined?
})
</script>
//唯一会出现undefined的情况是,你在呼叫save这个方法时没有传入value
//造成load在取值时出现undefined
下面例子
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function save(value) {
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = "savetThing" + "=" + encodeURI(value) + ";expires=" + exp.toGMTString();
}
function load() {
var cookies = document.cookie.split(";");
for( var i = 0; i < cookies.length ; i ++){
var cookieCrumbs = cookies[i].split("=");
var cookieName = cookieCrumbs[0];
var cookieValue = cookieCrumbs[1];
if( cookieName == "savetThing"){
document.getElementById("content").value=decodeURI(cookieValue);
}
}
}
function DelCookie() {
document.cookie = "savetThing"+"=;expires="+(new Date(0)).toGMTString();
reLoad();
}
function reLoad() { window.location.reload(); }
</script>
</head>
<body>
<input type="text" id="content" value="" style="width:300px;">
<input type="button" id="btn1" value="save" onclick="save('这是测试');">
<input type="button" id="btn2" value="load" onclick="load();">
<input type="button" id="btn3" value="del" onclick="DelCookie();">
</body>
</html>
//造成load在取值时出现undefined
下面例子
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function save(value) {
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = "savetThing" + "=" + encodeURI(value) + ";expires=" + exp.toGMTString();
}
function load() {
var cookies = document.cookie.split(";");
for( var i = 0; i < cookies.length ; i ++){
var cookieCrumbs = cookies[i].split("=");
var cookieName = cookieCrumbs[0];
var cookieValue = cookieCrumbs[1];
if( cookieName == "savetThing"){
document.getElementById("content").value=decodeURI(cookieValue);
}
}
}
function DelCookie() {
document.cookie = "savetThing"+"=;expires="+(new Date(0)).toGMTString();
reLoad();
}
function reLoad() { window.location.reload(); }
</script>
</head>
<body>
<input type="text" id="content" value="" style="width:300px;">
<input type="button" id="btn1" value="save" onclick="save('这是测试');">
<input type="button" id="btn2" value="load" onclick="load();">
<input type="button" id="btn3" value="del" onclick="DelCookie();">
</body>
</html>
温馨提示:答案为网友推荐,仅供参考