[英]Unable to assign an object with sessionStorage
I try to assign an object for further handling with jQuery but it doesn't work. 我尝试分配一个对象以使用jQuery进行进一步处理,但是它不起作用。 Here's my code:
这是我的代码:
$('.var').on('click', function () {
console.log($(this));
sessionStorage.setItem('object', JSON.stringify($(this)));
console.log(JSON.parse(sessionStorage.getItem('object')));
}
Both console logs don't have the same value. 两个控制台日志的值都不相同。 Why?
为什么?
Second example: 第二个例子:
$('.var').on('click', function () {
sessionStorage.setItem('object', JSON.stringify($(this)));
var item = JSON.parse(sessionStorage.getItem('object'));
item.addClass('not-work'); //does not work
$(this).addClass('work'); //works
e.preventDefault();
}
What am I doing wrong with sessionStorage(). sessionStorage()我在做什么错。
JSON.stringify strips methods from the stringified object, because valid JSON does not include functions. JSON.stringify从字符串化的对象中剥离方法,因为有效的JSON不包含函数。
Example: 例:
var obj = {
prop: 5,
method: function() {}
};
JSON.stringify(obj);
Result: "{"prop":5}"
结果:
"{"prop":5}"
@Ori Drori's answer explains the first example. @Ori Drori的答案解释了第一个例子。
In the second example, you get the DOM element (jquery wrapped), convert it to a string!
在第二个示例中,您将获得DOM元素(jquery包装),将其转换为
string!
and save in the sessionStorage. 并保存在sessionStorage中。
And then get this string
out of sessionStorage, do JSON.parse
in hope of getting the DOM element, but instead you'll get a javascript object which is certainly not an element in the DOM tree (as I believe you're expecting) & hence, calling .addClass
on it doesn't work. 然后从sessionStorage中获取此
string
,执行JSON.parse
以获取DOM元素,但是相反,您将获得一个javascript对象,该对象当然不是DOM树中的元素(正如我所期望的那样),因此,对其调用.addClass
不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.