javascript - 如何从 localStorage 访问超过 1 个元素?

标签 javascript storage local

我知道这可能是个愚蠢的问题,但我是新手,无法处理这个问题。

这是我的:

    <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/

相关文章:

javascript - 在 PHP 中解码字符串时出现意外行为(来自 AJAX POST 调用)

c++ - 退出程序MFC后保留变量值

javascript - 访问控制台中 Javascript 函数内的多个变量之一。

file - Sloot数字编码系统

hadoop - HDFS 中的存储格式

java - 本地 Java 应用程序 - 数据库选择

assembly - 为超过 4 字节的 x86 程序集 MASM 声明本地存储

javascript - 拉斐尔 Js : How to re-arrange the elements inside a raphael set in a curve path

javascript - 为什么我无法清除 Javascript 中的事件监听器?

javascript - 当资源不可用时,AngularJS 不断发送无效请求