【问题标题】:Insert a cookie to input value插入 cookie 来输入值
【发布时间】:2014-04-06 21:37:50
【问题描述】:

我有一个存储 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() + ",")

【问题讨论】:

标签: javascript jquery cookies textfield forms


【解决方案1】:

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

<input id="visitor">

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

【讨论】:

  • 很高兴为您提供帮助。请接受答案或至少投票。谢谢。
【解决方案2】:
document.getElementById('inputID').value = GetCookie('VisitorName');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多