2014-10-03 44 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