0

I am able to add the elements I want, but after I refresh they disappear. How can I get the elements to save permanently while using insertAdjacementHTML or do I need to use another method?

Sample code:

function itemAdder () {
    var header = document.querySelector(".list-group");
    header.insertAdjacentHTML("beforeend", '<a>Item 1</a>')
};

document.getElementById("circle-add").addEventListener("click", itemAdder)
4

1 回答 1

1

每次添加项目时,您可能会保存容器的当前innerHTMLin localStorage,并在页面加载时,如果存在任何内容,则localStorage使用存储的内容填充容器:

var header = document.querySelector(".list-group");
if (localStorage.headerHTML) header.innerHTML = localStorage.headerHTML;

function itemAdder () {
    header.insertAdjacentHTML("beforeend", '<a>Item 1</a>')
    localStorage.headerHTML = header.innerHTML;
}

document.getElementById("circle-add").addEventListener("click", itemAdder)

(希望您也有办法删除项目 - 删除时,使用同一行localStorage.headerHTML = header.innerHTML;再次保存 HTML)

于 2018-07-22T20:49:20.487 回答