【问题标题】:How do you save multiple key value pairs to one cookie with JavaScript/jQuery?如何使用 JavaScript/jQuery 将多个键值对保存到一个 cookie 中?
【发布时间】:2023-03-04 08:44:01
【问题描述】:

我有一个包含多个复选框的表单,当我单击它们时,我想在一个 cookie 中添加/删除键值对(输入名称 + 真/假)。

当我点击复选框时,只有第一对会显示在 console.log 中。

这是我目前为止的结果:

HTML:

<form class="form">
    <input class="input" name="expert_id_1" type="checkbox" />
    <input class="input" name="expert_id_2" type="checkbox" />
    <input class="input" name="expert_id_3" type="checkbox" />
    <input class="input" name="expert_id_4" type="checkbox" />
</form>

JS:

function setCookie() {
    var customObject = {};
    var inputName = $('.input').attr('name');
    customObject[inputName] = $('.input').prop('checked');
    var jsonString = JSON.stringify(customObject);
    document.cookie = 'cookieObject=' + jsonString;
    console.log(jsonString);
}

function getCookie() {
    var nameValueArray = document.cookie.split('=');
    var customObject = JSON.parse(nameValueArray[1]);
    $('.input').prop('checked') = customObject[inputName];
}

$('.input').each(function() {
    $(this).on('click', function() {
        if ($(this).is(':checked')) {
            $(this).attr('value', 'true');
        } else {
            $(this).attr('value', 'false');
        }
        setCookie();
    });
});

【问题讨论】:

标签: javascript jquery cookies key-value


【解决方案1】:

您的 cookie 被覆盖,它可能只存储第一个复选框信息。同样要设置 prop 值,您必须将其作为第二个参数传递。

这应该会在单击时更新 cookie,并且还可以从 cookie 中设置值。

function updateCookie($input) {
    var cookieObject = getCookieObject();
    var inputName = $input.attr('name');
    cookieObject[inputName] = $input.attr('value');
    var jsonString = JSON.stringify(cookieObject);
    document.cookie = 'cookieObject=' + jsonString;
    console.log(jsonString);
}

function setFromCookie(){
    var cookieObject = getCookieObject();
    for(var inputName in cookieObject)
        if(cookieObject.hasOwnProperty(inputName))
            $(`.input[name="${inputName}"]`).prop('checked', cookieObject[inputName]);
}

function getCookieObject() {
    var nameValueArray = document.cookie.split('=');
    var cookieObject = {};
    if(nameValueArray.length >= 2)
        cookieObject = JSON.parse(nameValueArray[1]);
    return cookieObject;
}

$('.input').each(function() {
    var $this = $(this);
    $this.on('click', function() {
        $this.attr('value', String($this.is(':checked')))
        updateCookie($this);
    });
});

虽然我建议您使用 URLSearchParams 对象来编码和解码参数,因为您依赖于 "=" 不在 JSON 字符串中的事实。

【讨论】:

  • 谢谢 Haibrayn González,这似乎解决了我的问题。
  • 我想添加一个函数,该函数将在文档上运行,准备仅检查 Cookie 中值为“true”的复选框,但我无法弄清楚如何过滤掉元素.
猜你喜欢
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多