使用localStorage的(短语可以在默认为falsey)
// save a flag
window.localStorage.setItem('iphone_no_redirect', 'true'); // any truthy string
// check a flag
if (window.localStorage.getItem('iphone_no_redirect')) {
// this has a truthy value
} else {
// this has a falsey value ("" or null)
}
// remove a flag
window.localStorage.removeItem('iphone_no_redirect');
// make flag falsy without removing it, set to ""
window.localStorage.setItem('iphone_no_redirect', '');
,如果你想知道,如果设置一个标志,你可以对证null
和falsey
// flag set but falsey
var x = window.localStorage.getItem('iphone_no_redirect');
if (!x && x !== null) { // x is falsey, x is not null
// ...
}
将此与confirm
结合,
function ask(question, key, overwrite) {
var response;
if (!overwrite) { // if not overwriting, check first
response = window.localStorage.getItem(key);
if (response !== null) { // has been asked before
if (['', 'false', 'no', '0', 'null', 'undefined'].indexOf(response) !== -1)
return false; // negative answers
return true; // anything else is a positive answer
}
}
if (overwrite === 2) { // easy cleanup
window.localStorage.removeItem(key);
return; // die
}
// not been asked before or we are overwriting previous answer
response = confirm(question);
window.localStorage.setItem(key, response.toString()); // "true" or "false"
return response;
}
在行动
console.log(ask('Are you human?', 'is_human')); // this causes confirm dialog
console.log(ask('Are you human?', 'is_human')); // this doesn't need to ask
// changing a previous answer
console.log(ask('Are you human?', 'is_human', 1)); // this causes confirm dialog again
// cleanup
ask(null, 'is_human', 2); // (don't need question for this)
如果什么用户点击错误地取消? – 2014-10-03 14:21:12
如果用户稍后擦除缓存,则会再次出现。但我不知道如何让cookie记住答案?这是我的主要问题。 – user3788491 2014-10-03 14:24:04
如果您不想将此信息传递给服务器并仅让客户端浏览器决定,请改为使用_localStorage_。 – 2014-10-03 14:45:35