我如何使这些动态元素可重用?

时间:2017-10-20 14:05:58

标签: javascript jquery

我在按钮点击时创建元素,文本作为值,id作为存储在localstorage中的键,我想在刷新或其他访问时重新创建它们。要做到这一点,我需要创建另一个相同的代码块,差别很小..我担心我可以简化这个但我想不出怎么做,我就要在createSet函数上使用clone()但是问题是否在页面上没有要克隆的默认元素。

ReminderSet.prototype.loadSet = function() {
    var keys = Object.keys(localStorage),
        i = 0,
        key,
        array;

    for (; key = keys[i]; i++) {
        const setId = localStorage.getItem(key);
        array = JSON.parse(setId); //parse and store key values
        let array_index = 0;
        //Re-create the reminders and set their properties//
        $reminderSection.append($('<div/>').addClass('set').attr('id', key) //Set the ID                      
            .append($('<div/>').addClass('set-title').append($('<h1>').attr('contenteditable', 'true').text(array[array_index].set_title)), //Index is always at 0//
                $('<div/>').addClass('create-reminder-control').append($('<button>').addClass('add-new-reminder').text("+ add new"), $('<input>').addClass('create-reminder-value').attr({ type: "text", placeholder: "get something done" })), $('<div/>').addClass('reminder-lists'), $('<div/>').addClass('save-control').append($('<button>').addClass('save-reminder-button').text('Save'))))

        //Get our key values //
        for (; array_index < array.length; array_index++) {
            /*Select the element id */
            $("#" + key).children('.reminder-lists').append($('<div/>').addClass('a-reminder').attr('contenteditable', 'true').text(array[array_index].description)) //Get the reminders
        } //end

    }
};

ReminderSet.prototype.createSet = function(id) {
    id = document.getElementsByClassName('set').length;
    id += 1;
    $reminderSection.append($('<div/>').addClass('set').attr('id', id)
        .append($('<div/>').addClass('set-title').append($('<h1>').attr('contenteditable', 'true').text('Reminders')),
            $('<div/>').addClass('create-reminder-control').append($('<button>').addClass('add-new-reminder').text("+ add new"), $('<input>').addClass('create-reminder-value').attr({ type: "text", placeholder: "get something done" })), $('<div/>').addClass('reminder-lists'), $('<div/>').addClass('save-control').append($('<button>').addClass('save-reminder-button').text('Save'))));
};
$('#create-set').click($.proxy(ReminderSet.prototype.createSet, ReminderSet));

var Reminder = function(description, set_title) {
    this.description = description;
    this.set_title = set_title;
    //Describes the reminder
};

ReminderSet.prototype.loadSet();

0 个答案:

没有答案