2014-10-03 25 views
0

我有這樣的代碼在我的index.html如何製作餅乾並記住iphone/android設備的答案?

if((navigator.userAgent.match(/iPhone/i))) { 
      if (document.cookie.indexOf('iphone_redirect=false') == -1) { 
       if (confirm('for your device exist iphone app')) { 
        window.location = 'https://itunes.apple.com/us/app/....'; 
       } 
      } 
     } 


     var ua = navigator.userAgent.toLowerCase(); 
     var isAndroid = ua.indexOf('android') > -1; 
     if(isAndroid) { 
      if (confirm('for your device exist iphone app')) { 
       window.location = 'https://play.google.com/store/apps/details?id=...'; 
      } 
     } 

但我不知道如何使餅乾記住我的答案。如果用戶單擊「取消」或「確定」記住「取消」或「確定」,直到用戶清除緩存。

你有沒有想法如何使cookie記住答案?

+0

如果什麼用戶點擊錯誤地取消? – 2014-10-03 14:21:12

+0

如果用戶稍後擦除緩存,則會再次出現。但我不知道如何讓cookie記住答案?這是我的主要問題。 – user3788491 2014-10-03 14:24:04

+0

如果您不想將此信息傳遞給服務器並僅讓客戶端瀏覽器決定,請改爲使用_localStorage_。 – 2014-10-03 14:45:35

回答

0

使用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) 
+0

謝謝你的幫助。這怎麼用我上面的例子來實現?你能幫忙嗎? – user3788491 2014-10-03 19:23:35

+0

謝謝你的回答。但是如何在第一篇文章中用我的代碼實現這個代碼? – user3788491 2014-10-05 06:46:02