我使用docCookies对象在this应用程序上设置Cookie。
我正在测试的功能就是这个:
displayWelcomeMessage = function(idElement){
var cookieName = 'username';
alert(docCookies.getItem(cookieName)); // NULL when cookie not set
var defaultName = "SweetAnon",
daysToExpire = 1,
username = docCookies.getItem(cookieName);
// Check if cookie was already set (user "logged")
if (username != null && username.trim() != "") {
displayUsername(idElement, username);
} else {
username = prompt("If you enter your name\nI'll try to remember you :)");
if (username != null && username.trim() != "") {
docCookies.setItem(cookieName, username, daysToExpire);
displayUsername(idElement, username);
} else {
displayUsername(idElement, defaultName);
}
}
alert(docCookies.getItem(cookieName)); // Username or 'SweetAnon'
};
这是两个警报,它们在Firefox v28和Chromium v33.0.1750.152之间打印出不同的结果。如果我将foobar
作为username
输入,我会得到以下结果:
null
然后foobar
。null
然后再打null
。我认为Firefox的行为是正确的。但是我应该怎样做才能使它在Chromium上运行?
答案 0 :(得分:1)
解决方案是将cookie值分配给对象而不是变量:
displayWelcomeMessage = function(idElement)
{
var cookieName = 'username',
defaultName = "SweetAnon",
daysToExpire = 1;
/* assign username as a property of the current function */
this.username = docCookies.getItem(cookieName);
alert(docCookies.getItem(cookieName)); // NULL when cookie not set
// Check if cookie was already set (user "logged")
if (this.username != null && this.username.trim() != "")
{
displayUsername(idElement, this.username);
}
else
{
this.username = prompt("If you enter your name\nI'll try to remember you :)");
if (this.username != null && this.username.trim() != "")
{
docCookies.setItem(cookieName, this.username, daysToExpire);
displayUsername(idElement, username);
}
else
{
displayUsername(idElement, defaultName);
}
}
alert(docCookies.getItem(cookieName)); // Username or 'SweetAnon'
};
<强>参考强>