如何使用javascript将链接设置为1小时的cookie?

时间:2012-09-09 06:33:37

标签: javascript html css

我有以下HTML:

   <a href="/index.html" title="Click only if you are sure of your browser">
       I'm warned, <strong>let me in anyway</strong></a>

有没有办法可以点击此链接首先将一个名为'forceAccess'的cookie设置为'yes'值,该值在我转到index.html之前的1天内到期?我有以下功能所以我想我只需要一种方法从上面调用它:

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

1 个答案:

答案 0 :(得分:1)

我认为您应首先检查cookie,然后您可以决定是否显示该链接。

以前评论中的w3schools链接可能有所帮助,但我也建议您使用jQuery,它可以帮助您以跨浏览器的方式操作DOM。

$(document).ready(function(){
   if(getCookie("thisPersonIsSure") != true) { //getCookie is just pseudo-code
       var theLink = $("<a href=\"/index.html\" title=\"Click only if you are sure of your browser\">I'm warned, <strong>let me in anyway</strong></a>").click(function(){createCookie("thisPersonIsSure", true, 1);});          
       $(document.body).append(theLink);
   } else {
       //Go to the index.html immediately e.g. by doing this:
       window.location.href = "/index.html";
   }
});

干杯!