将 cookie 读入文本框 (Javascript)

Reading a cookie into textbox (Javascript)

我写了一个 cookie 来保存卸载事件中 txtFirstName 的值。这是在卸载事件上完成的,因此无需提交按钮即可编写:

<head runat="server">
<title>Cookie Test</title>

<script type="text/javascript">
    function WriteCookies() {
        var d = new Date();
        var n = document.getElementById('txtFirstName').value;
        d.setDate(d.getDate() + 1);
        document.cookie = "CTFirstName = " + n +"; expires = " 
+ d.toGMTString() + "";
    }
</script>
</head>

<body onunload="WriteCookies()">

当有人关闭浏览器并再次打开时,我希望将 cookie 值读入文本框。但是我在完成这个时遇到了麻烦。谁能提供帮助?

谢谢!

添加读取 cookie 的功能。

这里是javascript部分

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

function GetCookies() {
    document.getElementById('txtFirstName').value = getCookie('CTFirstName');
}

这里是触发函数的 HTML 部分。

<body onunload="WriteCookies()" onload="GetCookies()">