做个笔记,以防忘记
遇到一个奇葩问题(书写规范不会遇到此问题
)
问题描述:
$(document).ready(function(){
var strCookie=document.cookie;
username="1";
if (strCookie) {
cookieVariables = strCookie.split(";");
for (i = 0; i < cookieVariables.length; i++) {
cookieName = cookieVariables[i].split("=");
if (cookieName[0] === "username"){
username=cookieName[1];
alert(cookieName[1]);
}
}
}
alert(username);
});
这样两次输出的username值不同第一个弹出的是Superman,第二个弹出“1”
解决办法:
将要赋的值通过一个function()方法的返回值获得
$(document).ready(function(){
var strCookie=document.cookie;
username=getname(username);
function getname(username){
if (strCookie) {
cookieVariables = strCookie.split(";");
for (i = 0; i < cookieVariables.length; i++) {
cookieName = cookieVariables[i].split("=");
if (cookieName[0] === username){
return cookieName[1];
alert("cookieName[1]");
}
}
}else{
return "1";
}
}
alert(username);
});