简体   繁体   English

HTML5本地存储以保存笔记

[英]HTML5 local storage to save notes

I created this note web app that allows the user to create several notes and navigate between them by using the various tabs on the left. 我创建了这个笔记web应用程序 ,允许用户创建几个笔记,并使用左侧的各个选项卡在它们之间导航。

Now I want these notes to save in the local storage so I added the following code: 现在我希望这些笔记保存在本地存储中,所以我添加了以下代码:

$(document).ready(function() {
    $(window).unload(saveSettings);
        loadSettings();
    });

    function saveSettings() {
        localStorage.notes = $('#notes').html();
    }

    function loadSettings() {
        $('#notes').html(localStorage.notes);
    }
}

It works in a certain degree. 它在一定程度上起作用。 Meaning the whole div is saved in the cache but for some reason when I reload the page I can see the different tabs but not the text that I wrote. 这意味着整个div保存在缓存中但由于某种原因,当我重新加载页面时,我可以看到不同的选项卡,但不能看到我写的文本。 Obviously the whole point is to save the notes so it's a problem if I can't see the text that I wrote. 显然,重点是保存笔记,这样如果我看不到我写的文字就会出问题。

I am unfortunately not so knowledgeable on javascript & jquery, so I have no idea what to do. 遗憾的是我不太了解javascript和jquery,所以我不知道该怎么做。

I believe it would be smarter to save each tabs and textarea individually in the cache instead of the whole Div but I also don't know how to do that. 我相信将每个标签和textarea单独保存在缓存而不是整个Div中更聪明,但我也不知道如何做到这一点。

If anyone can help me or at least guide me, it would be very appreciated. 如果有人可以帮助我或至少指导我,我将非常感激。

The "value" of a <textarea> field apparently does not become part of the innerHTML of that element, it's accessible instead via the .val() jQuery method or the .value DOM property. <textarea>字段的“值”显然不会成为该元素的innerHTML的一部分,而是可以通过.val() jQuery方法或.value DOM属性访问它。

It would be better to abstract the content of the tabs into eg an array, and recreate the DOM elements around those when you load the page. 最好将选项卡的内容抽象为例如数组,并在加载页面时围绕这些元素重新创建DOM元素。

This would ensure that if you redesign your content that old notes don't appear with the wrong rendering. 这将确保如果您重新设计内容,旧笔记不会出现错误的渲染。

For example (untested): 例如(未经测试):

function saveSettings() {
    var notes = $('#notes textarea').map(function(ix, el) {
        return el.value;
    });
    localStorage.notes = JSON.stringify(notes);
}

function loadSettings() {
    var notes = JSON.parse(localStorage.notes);

    // rebuilding divs left as exercise
    ...
}

I suggest you that you can use cookies to make notes In this is way you can store users notes for longer time 我建议您可以使用cookie来做笔记这样就可以将用户笔记存储更长时间

for more information about cookies you can check here : 有关cookie的更多信息,您可以在此处查看:

http://www.ms2fun.com/2015/01/javascript-cookies-getcookie-setcookie.html http://www.ms2fun.com/2015/01/javascript-cookies-getcookie-setcookie.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM