我正在尝试使用localStorage并尝试从div获取文本并将其存储在localStorage中,但是,它将其设置为[object Object]并返回[object Object]。为什么会这样?
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>
答案 0 :(得分:24)
您说您正在尝试从div获取文本并将其存储在本地存储中。
请注意:Text和Html不同。在你提到的问题中。 html()
将返回<a>example</a>
之类的Html内容。如果您想获取文字内容,则必须使用text()
代替html()
,结果将是example
而不是<a>example<a>
。无论如何,我使用你的术语让它成为文本。
第1步:从div获取文字。
你所做的不是从div获取文本,而是将文本设置为div。
$('#test').html("Test");
实际上是将文本设置为div,输出将是一个jQuery对象。这就是为什么它将其设置为[object Object]
。
要获得你必须这样写的文字
$('#test').html();
这将返回一个字符串而不是一个对象,因此结果将是Test
。
第2步:将其设置为本地存储空间。
您的方法是正确的,您可以将其写为
localStorage.key=value
但首选的方法是
localStorage.setItem(key,value);
设置
localStorage.getItem(key);
得到。
键和值必须是字符串。
所以在您的上下文中代码将变为
$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);
但是我的代码中没有任何意义。因为您想从div获取文本并将其存储在本地存储中。您再次从本地存储中读取相同内容并设置为div。就像a=10; b=a; a=b;
如果您遇到任何其他问题,请相应地更新您的问题。
答案 1 :(得分:15)
如果要将简单字符串写入localStorage,请使用setItem
和getItem
。如果你说的是你正在使用的文本,那么你应该使用text()
,否则你将获得完整的HTML作为字符串。
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// alert the value to check if we got it
alert(localStorage.getItem('test'));
的jsfiddle: https://jsfiddle.net/f3zLa3zc/
// get html
var html = $('#test')[0].outerHTML;
// set localstorage
localStorage.setItem('htmltest', html);
// test if it works
alert(localStorage.getItem('htmltest'));
的jsfiddle:
https://jsfiddle.net/psfL82q3/1/
当div的内容发生变化时,用户想要更新localStorage。由于不清楚div内容如何变化(ajax,其他方法?)contenteditable
和blur()
用于更改div的内容并覆盖旧的localStorage
条目。
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// bind text to 'blur' event for div
$('#test').on('blur', function() {
// check the new text
var newText = $(this).text();
// overwrite the old text
localStorage.setItem('test', newText);
// test if it works
alert(localStorage.getItem('test'));
});
如果我们使用ajax,我们会通过负责更新内容的函数来触发它。
的jsfiddle:
https://jsfiddle.net/g1b8m1fc/
答案 2 :(得分:3)
localStorage
只能存储字符串内容,并且您正在尝试存储jQuery对象,因为html(htmlString)
会返回一个jQuery对象。
您需要设置字符串内容而不是对象。并使用setItem
方法添加数据,使用getItem
获取数据。
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));