【问题标题】:After Click Event Instead of Showing all Notes Display only Current Note单击事件后,不显示所有注释,仅显示当前注释
【发布时间】:2019-11-09 09:27:59
【问题描述】:

程序从显示本地商店的所有笔记开始,但是当我单击添加按钮时,它只显示我当前的笔记。

我想显示所有笔记,点击事件后,新笔记将与以前的笔记一起添加。

let addButton = document.querySelector(".addBtn");
let userNotes = [];
displayNotes();
//addButton Event Listner
addButton.addEventListener("click", function(e) {
    e.preventDefault();

    //get the user inputs
    let userInputs = {
        title: document.getElementById("title_input").value,
        description: document.getElementById("des_input").value
    };

    //push user inputs to arrays
    userNotes.push(userInputs);

    document.querySelector("form").reset();

    //store to the localstorage
    localStorage.setItem("Notes", JSON.stringify(userNotes));

    //display to the user
    displayNotes();
});

function displayNotes() {
    let gettingNotes = localStorage.getItem("Notes");

    let allNotes = JSON.parse(gettingNotes);
    let html = "";
    allNotes.forEach(element => {
        html += `
                    <div class="single-item">
                        <h2 class="single-item-title">
                            ${element.title}
                        </h2>
                        <p class="single-item-description">
                            ${element.description}
                        </p>
                    </div>
                `;
    });

    document.querySelector(".item-list").innerHTML = html;
}

【问题讨论】:

    标签: javascript javascript-objects dom-events


    【解决方案1】:

    发生这种情况是因为您将 userNotes 设置为空数组并且只添加了当前注释。尝试使用 localStorage 中的值初始化 userNotes,即

    let userNotes = JSON.parse(localStorage.getItem('Notes')) || []
    

    另外,您可以在 displayNotes 函数中使用 userNotes 变量,而不是 allNotes。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2016-09-13
      • 1970-01-01
      相关资源
      最近更新 更多