javascript - 插入 cookie 以输入值

标签 javascript jquery cookies textfield forms

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

最佳答案

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

<input id="visitor">

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

关于javascript - 插入 cookie 以输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187424/

相关文章:

JavaScript 在 FF 和 IE 中不起作用

javascript - JQuery checkbox.prop ('checked' )总是返回 false 值

javascript - 如何确定是什么导致了 Polymer JS 中的事件触发?

java - HTTP 状态 406。Spring MVC 4.0、jQuery、JSON

javascript - 如何每 3 秒调用一个函数 15 秒?

javascript - 将 Cookie 保存为文件

javascript - Div selected - Unread Message - 像 facebook 收件箱一样阅读消息

ios - 如何在 UIWebView 中访问公共(public) Facebook 个人资料

javascript - Next.js v12 中间件不适用于 node-fetch 和 axios

javascript - 覆盖 jQuery ajax + 点击进入完整功能