使用jQuery设置和获取localStorage [英] Setting and getting localStorage with jQuery

查看:863
本文介绍了使用jQuery设置和获取localStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用localStorage并尝试从div获取文本并将其存储在localStorage中,但是,它将其设置为[object Object]并返回[object Object]。为什么会发生这种情况?

I am trying out localStorage and attempting at getting text from a div and storing it in localStorage, however, it sets it as an [object Object] and returns [object Object]. Why is this happening?

localStorage.content = $('#test').html('Test');

$('#test').html(localStorage.content);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test"></div>

推荐答案

您说您正在尝试从div获取文本将其存储在本地存储中。

请注意:文字和Html不同。在你提到的问题中。 html()将返回Html内容,例如< a>示例< / a> 。如果你想获得文本内容,那么你必须使用 text()而不是 html()然后结果将是示例而不是< a>示例< a> 。无论如何,我使用你的术语让它成为文本。

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

第1步:从div获取文本。

你所做的不是从div获取文本,而是将文本设置为div。

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

实际上是将文本设置为div,输出将是jQuery对象。这就是为什么它将它设置为 [object Object]

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

要获取文本,你必须像这样写

$('#test')。html();

To get the text you have to write like this
$('#test').html();

这将返回字符串不是对象,因此结果将是测试

This will return a string not an object so the result will be Test in your case.

步骤2:将其设置为本地存储。

Step 2: set it to local storage.

您的方法是正确的,您可以将其写为

Your approach is correct and you can write it as

localStorage.key=value

但首选方法是

localStorage.setItem(key,value); 设置

localStorage。 getItem(key); 获取。

键和值必须是字符串。

所以在你的上下文中代码将变为

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

但我的代码中没有任何含义。因为您想从div获取文本并将其存储在本地存储中。您再次从本地存储中读取相同内容并设置为div。就像 a = 10; B = A; a = b;

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

如果您遇到任何其他问题,请相应地更新您的问题。

If you are facing any other problems please update your question accordingly.

这篇关于使用jQuery设置和获取localStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆