使用javascript设置和检查cookie

时间:2015-04-03 18:15:38

标签: javascript html cookies

我有一个脚本,一旦点击链接就设置了一个cookie,然后当你再次访问该页面时,它将检查cookie并提醒你已经在这里。但是我的代码似乎不起作用。可以帮忙吗?



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
    <title></title>
    <script type="text/javascript">
        function get_cookie("visited"){
            if (document.cookie.indexOf("visited") >= 0) {
                // They've been here before.
                alert("hello again");
            }
    </script>

</head>

<body onload="get_cookie()">

    <script type="text/javascript">
        /*  This function sets the cookie   */
        function iLoveCookies() {
                days = 30; // number of days to keep the cookie
                myDate = new Date();
                myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString();
            }
            /*  end of cookie function  */


        
    </script>

    <a href="#" onclick="iLoveCookies()">Set Cookie</a>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

看起来你基本上有错误导致错误。您可能希望使用linter检查JavaScript,或者至少查看浏览器的developer console,看看它告诉您的内容。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
    <title></title>
    <script type="text/javascript">
        function get_cookie(){
            if (document.cookie.indexOf("visited") >= 0) {
                // They've been here before.
                alert("hello again");
            }
          }
    </script>
  

</head>

<body onload="get_cookie()">

    <script type="text/javascript">
        /*  This function sets the cookie   */
        function iLoveCookies() {
                days = 30; // number of days to keep the cookie
                myDate = new Date();
                myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString();
            }
            /*  end of cookie function  */
    </script>

    <a href="#" onclick="iLoveCookies()">Set Cookie</a>
    <a href="#" onclick="get_cookie()">Get Cookie</a>
</body>
</html>