wer*_*ewr 18 javascript jquery local-storage
我正在尝试localStorage并尝试从div获取文本并将其存储在localStorage中,但是,它将其设置为[object Object]并返回[object Object].为什么会这样?
localStorage.content = $('#test').html('Test');
$('#test').html(localStorage.content);Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>Run Code Online (Sandbox Code Playgroud)
Tin*_*aju 26
你说你正试图得到一个div文本和其存储在本地存储.
请注意:文本和Html是不同的.在你提到的问题中. html()将返回Html内容<a>example</a>.如果你想获得文本内容然后你必须使用text()而不是html()那么结果将是example而不是<a>example<a>.无论如何,我使用你的术语让它成为文本.
第1步:从div获取文本.
你所做的不是从div获取文本,而是将文本设置为div.
$('#test').html("Test");
Run Code Online (Sandbox Code Playgroud)
实际上是将文本设置为div,输出将是一个jQuery对象.这就是为什么它设置为[object Object].
要获得文本,你必须这样写
$('#test').html();
这将返回一个字符串而不是一个对象,因此结果将Test在您的情况下.
第2步:将其设置为本地存储.
你的方法是正确的,你可以把它写成
localStorage.key=value
Run Code Online (Sandbox Code Playgroud)
但首选的方法是
localStorage.setItem(key,value); 设置
localStorage.getItem(key); 要得到.
键和值必须是字符串.
所以在你的上下文代码将成为
$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);
Run Code Online (Sandbox Code Playgroud)
但是我的代码中没有任何意义.因为您想从div获取文本并将其存储在本地存储中.你再次从本地存储中读取相同内容并设置为div.就像a=10; b=a; a=b;
如果您遇到任何其他问题,请相应地更新您的问题.
Tom*_*mie 24
使用setItem和getItem如果你想要写简单的字符串到localStorage的.你也应该使用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'));
Run Code Online (Sandbox Code Playgroud)
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'));
Run Code Online (Sandbox Code Playgroud)
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'));
});
Run Code Online (Sandbox Code Playgroud)
如果我们使用ajax,我们将通过负责更新内容的函数触发函数.
JSFiddle:https://jsfiddle.net/g1b8m1fc/
只能localStorage存储字符串内容,并且您正在尝试存储 jQuery 对象,因为html(htmlString)返回一个 jQuery 对象。
您需要设置字符串内容而不是对象。并使用该setItem方法添加数据和getItem获取数据。
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74408 次 |
| 最近记录: |