[英]store the localstorage value in the form of json
嗨,我正在嘗試在本地存儲中保存一些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
。 舉例來說,如果我想的name
您的input
內容是要在對象上使用的名稱:
$('.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 = "";
}
});
}
編寫localstorage時只有2個參數:
例如 localStorage.setItem('car',car); 第一個參數實際上是鍵,第二個參數是值;
您通過了3個參數,這是錯誤的。
如果可以在localstorage中存儲多個值,請創建該值的對象並將該對象寫入localstorage:
ex.
var car = {};
car.wheels = 4;
car.doors = 2;
car.sound = 'vroom';
car.name = 'Lightning McQueen';
console.log( car );
localStorage.setItem('car', JSON.stringify(car));
console.log( JSON.parse( localStorage.getItem( 'car' ) ) );
我認為這會有所幫助。
var objectToSave = {};
$('.proceed_btn').on('click', function(){
$('input[type="text"],input[type="hidden"]').each(function(){
var elem = $(this);
var id = elem.attr('id');
var value = elem.val();
objectToSave[id] = value;
});
localStorage.setItem('order', JSON.stringify(objectToSave));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.