我一直试图在我的网页中使用本地存储和文本区域(没有效果)。
我的保存脚本如下:
$(function() {
var editor = document.querySelector("#editor");
editor.addEventListener("keyup", function() {
window.localStorage["TextEditorData"] = editor.value;
});
});
我的加载脚本如下:
$window.load(function () {
var editor = document.querySelector("#editor");
if (window.localStorage["TextEditorData"]) {
editor.value = window.localStorage["TextEditorData"];
}
});
我的HTML5代码如下:
<!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>
但似乎没用。我是不是遗漏了一些显而易见的东西?当我使用contenteditable div而不是textarea,使用editor.innerHTML而不是editor.value时,我确实成功地让它工作了,但是我需要为这个特定的网页使用textarea。有什么建议吗?
最佳答案
您的if()
缺少一些括号,这是:
if window.localStorage["TextEditorData"] {
应该是:
if (window.localStorage["TextEditorData"]) {
目前它抛出了一个语法错误。Here's a version of your code with the above fix,工作:)