JavaScript函数deleteCookie()不适用于我

时间:2016-02-02 20:30:30

标签: javascript function cookies

我正在尝试学习JavaScript,并试图创建一个删除cookie的按钮,但我的代码根本无法正常工作,我已经被困在这几个小时了。

为方便起见,该页面位于此处: http://kazmer.x10host.com/Week4/delete_cookie_test.html

cookie.js位于: http://kazmer.x10host.com/Week4/cookies.js

外部cookies.js中的代码如下:

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

function getCookie(name) {
    var nameEquals = name + "=";
    var crumbs = document.cookie.split(';');
    for (var i = 0; i < crumbs.length; i++) {
        var crumb = crumbs[i].trim();
        if (crumb.indexOf(nameEquals) == 0) {
            return unescape(crumb.substring(nameEquals.length,crumb.length));
        }
    }
    return null;
}

页面的HTML中还包含一些JS:

 <!DOCTYPE html>

 <html lang="en-US">

 <head>
 <title>Delete Cookie Test</title>
 <meta charset="UTF-8" />
 <meta name = "description" content = "JavaScript Test" />

 <script src="cookies.js"></script>

 <script>

    window.onload = function() {
        var cookievalue = prompt("Cookie Value:");
        createCookie("myCookieData", cookievalue);
    }

    function viewCookieInfo() {
        document.getElementById("output").innerHTML = "Your cookie value: " + getCookie("myCookieData");
    }

    function deleteCookie(name) {
        name="myCookieData";
        createCookie(name,"",-1);
    }

 </script>

 </head>

 <body>

 <button type="button" onclick="viewCookieInfo()" >Display Cookie Info</button><br>
 <div id="output"></div><br>
 &nbsp &nbsp <button type="button" onclick="deleteCookie()" >Delete Cookie</button>

 </body>

 </html>

我理解将cookie过期的概念,但它只是不起作用,我希望有人会在这里指出我的错误。

提前谢谢!

0 个答案:

没有答案