功能和本地存储问题

时间:2017-12-15 00:34:41

标签: javascript functional-programming local-storage

此代码最初使用input.value并将其添加到页面中。我在本项目中添加了本地存储,代码已经写好了,但我很难从localStorage显示页面输入。输入作为数组中的对象存储在本地存储中。我编写了一个for循环来循环遍历这些值并将它们传递给构建元素的函数并将其附加到li并稍后附加到ul。它没有显示在页面上,我在控制台中没有出现任何错误。我不确定在哪里转,所以继承我的代码:

function fetchInvite() {
     const rsvpInvite = JSON.parse(localStorage.getItem("Invitees"));
     const rsvpList = document.getElementById('invitedList'); 

    for(var i = 0; i < rsvpInvite.length; i++) {
        const name = rsvpInvite[i].name;
        const confirm = rsvpInvite[i].confirmed;
        createLI(name, confirm);

    function createLI(name, confirm) {
        const li = document.createElement('li');

    function createElement(elementName, property, value) {
        const element = document.createElement(elementName);

        element[property] = value;
        return element;
    }
    function appendToLI (elementName, property, value) {
        const element = createElement(elementName, property, value);
        li.appendChild(element);
        return element;
    }

appendToLI('span', 'textContent', name);
appendToLI('label', 'textContent', confirm)
.appendChild(createElement('input', 'type', 'checkbox'));
appendToLI('button', 'textContent', 'edit');
appendToLI('button', 'textContent', 'remove');
return li;

}

} }

完整项目可在此处获取:https://github.com/tianniNakiMyers/RSVP_TeamTreeHouse/blob/master/app.js

1 个答案:

答案 0 :(得分:0)

您的代码存在的问题是您可能从未调用fetchInvite

除此之外,这里是您的代码的重构:

function elt(parent, tag, text) {                                        // create element of tagname tag and append it to a parent (if provided) then set its textContent to text and return it
    var el = document.createElement(tag);
    if(parent) {
        parent.appendChild(el);
    }
    el.textContent = text;
    return el;
}

function fetchInvite() {
    const rsvpInvite = JSON.parse(localStorage.getItem("Invitees"));
    const rsvpList = document.getElementById('invitedList');

    for(var i = 0; i < rsvpInvite.length; i++) {
        const name = rsvpInvite[i].name;
        const confirm = rsvpInvite[i].confirmed;

        const li = elt(rsvpList, 'li', '');                              // create an li element with empty text and append it to rsvpList
        elt(li, 'span', name);                                           // create a span whose text is name and append it to li
        elt(elt(li, 'label', confirm), 'input', '').type = 'checkbox';   // create an input append it to a label element that contain the text confirm and that is appended to li, then set type of input to 'checkbox'
        elt(li, 'button', 'edit');                                       // ...
        elt(li, 'button', 'remove');
    }
}

fetchInvite(); // don't forget to call it