将cookie插入输入值

时间:2014-03-05 02:42:36

标签: javascript jquery cookies textfield html-form

我有一个存储cookie值的JavaScript函数,我希望将其插入到HTML表单的字段中(如在Facebook中 - 在注销后预先填写您的电子邮件)。

Cookie最初显示为document.write

我想我必须:

  • 获取VisitorName Cookie
  • 的值
  • document.write转换为文字
  • 通过

    更改输入值来插入此文本
    document.getElementById('inputID').value = cookie value"
    

我该怎么做?这是代码:

var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function Who(info) {
    var VisitorName = GetCookie('VisitorName')

    if (VisitorName == null) {
        VisitorName = "Dear visitor";
        SetCookie ('VisitorName', VisitorName, exp);
    }

    return VisitorName;
}

function set() { 
    VisitorName = prompt("");
    SetCookie ('VisitorName', VisitorName, exp);
}

function getCookieVal (offset) {
    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1)
        endstr = document.cookie.length;

    return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;

    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0)
            break;
    }

    return null;
}

function SetCookie (name, value) {
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc>2) ? argv[2] : null;
    var path = (argc >3) ? argv[3] : null;
    var domain = (argc >4) ? argv[4] : null;
    var secure = (argc >5) ? argv[5] : false;
    document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : (";expires=" + expires.toGMTString())) +
        ((path == null) ? "" : (";path=" + path)) +
        ((domain == null) ? "" : (";domain=" + domain)) +
        ((secure == true) ? ";secure" : "");
}

function DeleteCookie (name) {
    var exp = new Date();
    exp.setTime (exp.getTime() - 1);

    var cval = GetCookie (name);
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

document.write("" + Who() + ",")

2 个答案:

答案 0 :(得分:1)

您的帖子已经回答了您自己的问题。将列表放在一起:

<input id="visitor">

<script>
document.getElementById('visitor).value = GetCookie('VisitorName');
</script>

答案 1 :(得分:1)

document.getElementById('inputID').value = GetCookie('VisitorName');