如何使localStorage数据跨页面持久化?

时间:2014-01-10 20:44:11

标签: jquery json local-storage

我正在构建一个便利贴页面。我想保存创建的笔记。数据与localStorage()一起保存,这使得数据在页面重新加载时保持不变,但在向其他页面冲浪时则不会。从其他页面返回时,如何使笔记保存?

   var notes, count = 0;

function saveNotes() {
    var notesArray = [];
    notes.find("li > div").each(function (i, e) {
        var title = $(e).find("input.note-title");
        var content = $(e).find("textarea.note-content");

        notesArray.push({ Index: i, Title: title.val(), Content: content.val() });
    });

    var jsonStr = JSON.stringify(notesArray);

    localStorage.setItem("notes", jsonStr);
}

function addNoteEvent(noteElement) {
    var div = noteElement.children("div");
    var closeIcon = div.find("i");

    div.focus(function () {
        closeIcon.removeClass("hidden");
    });

    div.hover(function () {
        closeIcon.removeClass("hidden");
    }, function () {
        closeIcon.addClass("hidden");
        saveNotes();
    }) 
}

function addNewNote(className, title, content) {

    notes.append("<li><div class='col-md-3 portfolio-item img'>" + 
                    "<input class='note-title' placeholder='Untitled'/>" + 
                    "<i class='fa fa-trash-o hidden'></i>" +
                    "<textarea class='note-content' placeholder='Your content here'/>" +  
                "</div></li>");

    var newNote = notes.find("li:last");
    newNote.find("i").click(function () {
        newNote.remove();
        saveNotes();
    });

    addNoteEvent(newNote);


    if (title) {
        newNote.find("input.note-title").val(title);
    }
    if (content) {
        newNote.find("textarea.note-content").val(content);
    }
    saveNotes();
}

function loadNotes() {
    var storedNotes = localStorage.getItem("notes");
    if (storedNotes) {
        var notesArray = JSON.parse(storedNotes);
        count = notesArray.length;

        var i;
        for (i = 0; i < count; i++) {
            var storedNote = notesArray[i];
            addNewNote(storedNote.Class, storedNote.Title, storedNote.Content);
        }
    }
}

$(document).ready(function () {
    notes = $("#notities .container > .row");

    loadNotes();
    $(".btnNew").click(function () {
        addNewNote();
    });

    if (count === 0) {
        $(".btnNew").click();
    }
});

1 个答案:

答案 0 :(得分:1)

localStorage在同一域中的页面中保持不变。普通的同源规则适用于DOM storage,因此只要您的网页位于同一个域中,就可以访问这些数据。