简体   繁体   English

如何在 localstorage 中添加和删除关键组件?

[英]How do I add and remove a key component in localstorage?

I got a big problem right here.I need the product to be added as an "Espresso" key child,and the key child to be removed on click of the "REMOVE button".Here goes my code:我在这里遇到了一个大问题。我需要将产品添加为“Espresso”关键子项,并且在单击“删除按钮”时要删除关键子项。这是我的代码:

let pList = document.getElementById("productList")

//Espresso

const addEspresso = () => {   var Espresso, esp, eObj;   Espresso = {
    name: "Espresso",
    type: "strong",
    imgSrc: "images/c7.png"   };

  localStorage.setItem("Espresso", JSON.stringify(Espresso));

  esp = localStorage.getItem("Espresso");   eObj = JSON.parse(esp);

  let htmlEspresso = "";   htmlEspresso += `
         <div class="productDiv">
         <p>${eObj.name}</p> 
         <p>${eObj.type}</p>
         <img src="${eObj.imgSrc}">
         <button class="btn-remove">REMOVE</button>
         </div>
         `

  document.getElementById("productList").innerHTML += htmlEspresso 
}
document.addEventListener("click", function(e) {
  var btnR = document.getElementsByClassName("btn-remove");
  if (e.target.classList.contains("btn-remove")) {
    e.target.closest(".productDiv").remove();
    localStorage.removeItem(e.target.parentElement.querySelector('p').textContent);
  }
})

Here goes an example of what I want这是我想要的一个例子

You are trying to access the child text (first p tag) after removing it's parent (.productDiv).您试图在删除其父级 (.productDiv) 后访问子文本(第一个 p 标记)。 Do this instead:改为这样做:

if (e.target.classList.contains("btn-remove")) {
     localStorage.removeItem(e.target.parentElement.querySelector('p').textContent);
     e.target.closest(".productDiv").remove(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM