【问题标题】:Pop-up windows save in local storage弹出窗口保存在本地存储中
【发布时间】:2016-04-05 10:00:41
【问题描述】:

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

【问题讨论】:

  • document.getElementById("note").placeholder = "notes" ; 这是一个语法错误。
  • 你正在将用户作为变量但设置注释var user = document.getElementById("note").value ; localStorage.setItem("note", note) ;
  • 检查这一行 localStorage.setItem("note", note) ;我认为你需要把用户放在 note.like 这个 localStorage.setItem("note", user) ;
  • Ech.. 还是不行:( jsfiddle.net/venntr/14fs0fef/12

标签: javascript jquery local-storage


【解决方案1】:

您的解决方案存在一些问题。首先,保存便笺的单击事件不起作用,因为选择器出现错误,因为它在第一次加载时在页面上找不到“保存”的 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”),或者更好的解决方案可能是在页面上设置一个主保存按钮来保存所有便签。然后您可以遍历它们并将它们全部保存为本地存储中的 JSON 数组:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多