使用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