弹出窗口保存在本地存储中

Pop-up windows save in local storage

本文关键字:存储 存在 窗口 保存      更新时间:2023-09-26

我仍然尝试在本地存储便签。我想在打开之前自动查看(打开)所有的粘性,当页面被刷新这么长时间,直到它们被ESC关闭。ESC关闭工作,但本地存储无法保存粘性。。。

https://jsfiddle.net/venntr/14fs0fef/3/

if (localStorage["note"])
{
    var user = localStorage["note"] ;
    document.getElementById("note").value = user ;
}
else
{
    document.getElementById("note").placeholder = "notes" ;
    console.log("notes not found in localStorage")
}
document.getElementById("save").addEventListener("click", function ()
{
    var user = document.getElementById("note").value ;
    localStorage.setItem("note", note) ;
    alert("note id saved") ;
} , false);
function closeIt(that) {
    var cls = parseInt(that.parent().parent().attr('class').split(' ')[1]);
    var index = arr.indexOf(cls);
    console.log('.note.'+cls+' '+index);
    arr.splice(index,1);
    that.parent().parent().remove();
}

您的解决方案有几个问题。首先,保存便笺的点击事件不起作用,因为选择器在第一次加载时在页面上找不到"保存"的id(因为还没有创建便笺),因此出现错误。既然您已经在使用jQuery,那么您应该将它用于所有的选择器,因为它没有这个问题。

$(document).on("click", 'button.savebutton', function ()
{
    var note = document.getElementById("note").value ;
    localStorage.setItem("note", note) ;
    alert("note id saved") ;
});

其次,当您使用jQuery设置文本区域的值时,您需要使用"val"方法:

$("textarea#note").val(note);

然而,这仍然不能让你到达你想要的地方,因为当页面加载时,还没有可以加载你的值的便签(除非你有更多的代码没有显示)。您需要循环使用从本地存储返回的值,并从中动态创建便签。类似于:

for (var i = 0; i < notes.length;i++) {
        addNote(notes[i]);
}

其中addNote应该是一个函数,您可以在其中创建一个新的便笺,就像您在"添加便笺"按钮单击事件中所做的那样。

编辑:

还有一个问题,您的解决方案只允许保存一个便签,因为保存单击事件会覆盖您已经放入本地存储的任何其他内容。您需要为本地存储中的每个粘贴都有唯一的名称(即"note1"、"note2"),或者更好的解决方案可能是在页面上有一个主保存按钮,可以保存所有粘贴。然后,您可以循环遍历它们,并将它们全部保存为本地存储中的JSON数组:

localStorage.setItem('notes', JSON.stringify(noteArray));

实际上,你可以完全放弃保存按钮,并在使用退出页面时保存所有内容:

$(window).on('beforeunload', function() {
       //loop over notes and put in array
       //stick json array in localstorage
});
相关文章: