繁体   English   中英

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

[英]Pop-up windows save in local storage

我仍然尝试在本地存储便签。 我想在打开粘性之前自动查看(打开)所有内容,因为页面将刷新很长时间直到它们将被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();
}

您的解决方案有几个问题。 首先,用于保存便笺的click事件无法正常工作,因为选择器出现错误是因为选择器在首次加载时无法在页面上找到“保存”的ID(因为尚未创建便笺) 。 由于您已经在使用jQuery,因此应将其用于所有选择器,因为它没有此问题。

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

其次,当您使用jQuery设置textarea的值时,您需要使用'val'方法:

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

但是,这仍然无法满足您的需要,因为在页面加载时,还没有便笺将值加载到其中(除非您有更多未显示的代码)。 您需要遍历从本地存储返回的值,并根据它们动态创建便签。 就像是:

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

其中addNote应该是一个功能,您可以像在“添加便笺”按钮单击事件中一样创建新的便笺。

编辑:

另一个问题是,您的解决方案仅允许保存一个便签,因为保存点击事件将覆盖您已经放入本地存储中的所有内容。 您需要为本地存储中的每个即时贴都具有唯一的名称(即“ note1”,“ note2”),或者更好的解决方案可能是在页面上具有一个主保存按钮来保存所有即时贴。 然后,您可以遍历它们,并将它们全部保存为localstorage中的JSON数组:

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

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

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

暂无
暂无

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

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