首页 文章

如何从存储在sessionStorage中的JSON值中检索特定对象?

提问于
浏览
0

我把它存储在会话中:

我想要做的是将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')));

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

2 回答

  • 0

    多次从 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']);
        }
    }
    
  • 1

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

    那些选择键的建议不是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)
       });
    }
    

相关问题