gpt4 book ai didi

javascript - 以json形式存储localstorage值

转载 作者:行者123 更新时间:2023-12-03 07:02:07 24 4
gpt4 key购买 nike

您好,我正在尝试在本地存储中保存一些 input[type="text"] 和 input[type="hidden"] 值。下面是JS:

$('.proceed_btn').on('click', function(){

$('input[type="text"]').each(function(){
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});
$('input[type="hidden"]').each(function(){
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});

});

该值已完美存储。但我想以 json 格式存储这些值。但如何将这两个值保存在一个变量中。例如:

order: {
id: '',
product: '',
service: '',
name: ''
}

我已经检查了 JSON stringify 但如何同时实现不同类型的输入

最佳答案

简单地构建一个对象,然后对其进行字符串化。例如,如果我假设您的 input 元素的 name 是您要在对象上使用的名称:

$('.proceed_btn').on('click', function(){
// Blank to start with
var order = {};

// Loop through all inputs...
$('input[type="text"], input[type="text"]').each(function(){
// ...adding their values as properties
order[this.name] = this.value;
});

// Store that object in JSON format
localStorage.setItem("order", JSON.stringify(order));
});

稍后,如果您想检索它并根据其值设置输入:

var order = JSON.parse(localStorage.getItem("order") || "null");
if (order) {
$('input[type="text"], input[type="text"]').each(function(){
if (this.name in order) {
this.value = order[this.name];
} else {
this.value = "";
}
});
}

关于javascript - 以json形式存储localstorage值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37000002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com