我知道这可能是个愚蠢的问题,但我是新手,无法处理这个问题。
这是我的:
<div class="form-group">
<label for="category">Choose category:</label>
<select class="form-control" id="category">
<option>food</option>
<option>drinks</option>
<option>bills</option>
<option>others</option>
</select>
<textarea type="text" id="price" class="input-inline"></textarea>
</div>
<textarea type="text" id="name" class="input-inline"></textarea>
<div id="DisplayItem"></div>
<a href="#" data-role="button" onclick="SaveItem()" style="width:120px;margin:auto">Save it</a>
<a href="#" data-role="button" onclick="DisplayItem()" style="width:150px;margin:auto">Display it</a>
</form>
和脚本:
function SaveItem() {
localStorage.setItem("category", jQuery("#category").val());
}
function DisplayItem() {
jQuery('#DisplayItem').text(localStorage.getItem("category"));
}
使用此代码,我将仅获取类别,但我想获取所有字段的值。 例如,我希望得到如下结果: 您的类别是“C”,名称是“N”,价格是“P”。其中 C、N 和 P 代表公式中的值。 一个功能怎么实现?
谢谢
最佳答案
最好的选择是将所有相关数据作为一个对象进行管理。
function SaveItem() {
var item = {
category: jQuery("#category").val(),
name: jQuery("#name").val(),
price: jQuery("#price").val()
};
localStorage.setItem("item", JSON.stringify(item)); //JSON.stringify() transforma el objeto en un string en formato JSON para poder guardarlo
}
function DisplayItem() {
var item = JSON.parse(localStorage.getItem("item")); //JSON.parse() transforma un string en formato JSON un objeto
var output = "Category: " + item.category + " - Price: " + item.price + " - Name: " + item.name;
jQuery('#DisplayItem').text(output);
}
关于javascript - 如何从 localStorage 访问超过 1 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37123342/