localstorage多个值

时间:2016-05-10 12:52:30

标签: javascript jquery arrays html5

好吧,所以我有文本框输入成绩,然后将它们保存在localstorage中,我可以在我的文本框下看到它们。但是,如果我想添加更多文本框,我可以在其中添加更多成绩,并且它们将保存在localstorage中,但它们将在另一个数组中,或者我将如何做到这一点?我将不胜感激任何帮助。

$(document).ready(function () {
    var i = 0;
    for (i = 0; i < localStorage.length; i++) {
        var gradeID = "grade-" + i;
        $('#gradeList').append("<b id='" + gradeID + "'>" + localStorage.getItem(gradeID) + "</b>, ");
    }

    $('#clear').click(function () {
        localStorage.clear();
    });

    $('#gradeEntryForm').submit(function () {
        if ($('#gradeInput').val() !== "") {
            var gradeID = "grade-" + i;
            var gradeMessage = $('#gradeInput').val();
            localStorage.setItem(gradeID, gradeMessage);
            $('#gradeList').append("<b class='task' id='" + gradeID + "'>" + gradeMessage + "</b>, ");
            var grade = $('#' + gradeID);
            task.slideDown();
            $('#gradeInput').val("");
            i++;
        }
        return false;
    });

    $('#gradeList').on("click", "b", function (event) {
        self = $(this);
        gradeID = self.attr('id');
        localStorage.removeItem(gradeID);
        self.remove();

    });


});

DEMO

2 个答案:

答案 0 :(得分:0)

您可以将动态ID设置为LocalStorage键,您可以将其与生成的TextBox相关联

如下所示

localStorage['grade_' + some_id] = value;

答案 1 :(得分:0)

您可以使用以下示例:

document.getElementById("addGrade").onclick = function() { var gradeCell = document.getElementById("gradeCell"); var input = document.createElement("input"); input.type = "number"; var br = document.createElement("br"); gradeCell.appendChild(input); gradeCell.appendChild(br); }

EXAMPLE