【问题标题】:How to retrieve a specific object from a JSON value stored in sessionStorage?如何从 sessionStorage 中存储的 JSON 值中检索特定对象?
【发布时间】:2019-05-10 05:45:39
【问题描述】:

我已将其存储在会话中:

我要做的是将 JSON 中的每个对象分配为一个变量,以便我可以将它们适当地添加到 DOM。

这可行,但会打印出所有内容:

if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
    $(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}

我想要的是这样的,但它不起作用:

var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: javascript session cookies session-cookies session-storage


    【解决方案1】:

    多次从storage 获取相同的值不是一个好主意。此外,您需要更好的变量名称。

    var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
    if (json) {
        var data = JSON.parse(json);
        if (data) {
            var cart_link = $(data['a.cart-contents']),
            footer_link = $(data['a.footer-cart-contents']),
            widget_div = $(data['div.widget_shopping_cart_content']);
        }
    }
    

    【讨论】:

    • 谢谢,这很干净,正是我所需要的。非常感谢!
    【解决方案2】:

    看来您已将选择器设置为对象的键,因此您可以迭代这些键以获取每个选择器。

    这些选择键的建议并不是 100% 明确的。我假设这些选择器是您要插入 html 字符串的元素,$() 表示您正在使用 jQuery

    if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
        var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
    
       $.each(data, function(selector, htmlString){
          $(selector).append(htmlString)
       });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2020-08-09
      • 2013-10-15
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多