2012-02-17 73 views
1

所以我試圖做一個簡單的便箋thingy使用localstorage你可以鍵入並自動保存。在localstorage上保存換行

當我按下換行符時,出現問題。本地存儲不適用換行符。

HTML:

<div contenteditable="true" class="s_content">Type something, press linebreak and type something again. Then refresh</div>​ 

JS:

$('div.s_content').text(localStorage.getItem ("foo")) 

$("div.s_content").on("keyup paste", function() { 
localStorage.setItem ("foo", $('div.s_content').text()) 
});​ 

例子:http://jsfiddle.net/z2e6Y/

嘗試輸入一些東西,按回車鍵並輸入更多的東西。然後刷新頁面。

如何將<br>/line-break應用於本地存儲?

回答

2

同時改變你的.text()調用爲.html (),它應該工作:

$('div.s_content').html(localStorage.getItem ("foo")) 

$("div.s_content").on("keyup paste", function() { 
    localStorage.setItem ("foo", $('div.s_content').html()); 
});​ 

http://jsfiddle.net/k4dWX/3/

由於您使用的是標籤,因此其中的數據是HTML而不僅僅是文本。因此,您需要使用br或div標籤將div.s_content的內容設置爲HTML,而不僅僅是換行符。如果您從其他位置拉取文本,則需要先將換行符轉換爲br或div標籤。

+0

爲什麼我沒有想到這一點。謝謝 – jQuerybeast 2012-02-17 07:37:33

0

我的事情,我得到了烏拉圭回合的問題,

烏爾在Ajax調用保存數據,這樣

通價值,

if u use 
    $('#container').html(); // You ll get html tags with text 
    //like this-----------> teste<br><br><br>r 
else 
    $('#container').text(); // You ll get only text 
    //like this -----------> tester 

try console and check buddy, 

console.log('----------->'+$('#container').html()); 
console.log('----------->'+$('#container').text()); 


Your coding: 

$('div.s_content').text(localStorage.getItem ("foo")) 


$("div.s_content").on("keyup paste", function() { 
    localStorage.setItem ("foo", $('div.s_content').html()) // changes has to Here text to html 
}); 
+0

這就是答案。由於斯多利夫用同樣的答案更快地回答,我選擇他作爲正確的答案。謝謝 – jQuerybeast 2012-02-17 08:10:28