[英]How to retrieve a specific object from a JSON value stored in sessionStorage?
I have this stored in the session: 我将其存储在会话中:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately. 我要做的是将JSON中的每个对象分配为变量,以便可以将它们适当地添加到DOM中。
This works but prints everything out: 这可以工作,但可以打印出所有内容:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work: 我想要的是这样的东西,但是不起作用:
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')));
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you! 谢谢!
Getting the same value from the storage
several times is not a good idea. 多次从storage
获取相同的值不是一个好主意。 In addition, you need better names for your variables. 另外,您需要为变量使用更好的名称。
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']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector. 如此看来,您已将选择器设置为对象的键,因此可以迭代这些键以获取每个选择器。
The propose of those selector keys is not 100% clear. 这些选择键的提议不是100%明确的。 I am assuming that those selectors are the elements you want to insert the html strings into and that $()
means you are using jQuery 我假设这些选择器是您要将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)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.