使用 javascript 设置和检查 cookie

Setting and Checking cookies with javascript

我有一个脚本,可以在单击 link 后设置 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>

看来您基本上是拼写错误导致了这些错误。您可能想使用 linter to check your JavaScript or at the least look at your browser's 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>