开发者

HTML5 localStorage with a textarea

开发者 https://www.devze.com 2023-01-09 13:52 出处:网络
I\'ve been trying to use localStorage with a textarea in my webpage (to no avail). My save script is as follows:

I've been trying to use localStorage with a textarea in my webpage (to no avail).

My save script is as follows:

$(function() {
 var editor = document.querySelector("#editor");
 editor.addEventListener("keyup", function() {
  window.localStorage["TextEditorData"] = editor.value;
 });
});

My load script is as follows:

$window.load(function () {
 var editor = document.querySelector("#editor");
 if (window.localStorage["TextEditorData"]) {
  editor.value = window.localStorage["TextEditorData"];
 }
});

My HTML5 code is as follows:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/data-load.js"></script>
<script type="text/javascript" src="js/data-save.js"></script>
</head>
<body onLoad="开发者_运维技巧editor.focus()">
<textarea id="editor"></textarea>
</body>
</html>

But it doesn't seem to work. Am I missing something obvious here? I did manage to get it to work when I used a contenteditable div instead of a textarea and with editor.innerHTML instead of editor.value but I need to use a textarea for this particular webpage. Any suggestions?


You're missing some parenthesis on your if(), this:

 if window.localStorage["TextEditorData"] {

Should be:

 if (window.localStorage["TextEditorData"]) {

Currently it's throwing a syntax error. Here's a version of your code with the above fix, working :)

0

精彩评论

暂无评论...
验证码 换一张
取 消