首页 > 解决方案 > 如何通过访问其 id 从本地存储和 html 中删除元素

问题描述

这是一个非常基本的抽认卡游戏,您可以在其中键入一个问题和一个主卡的答案,然后通过单击保存按钮在存储中创建一个新的抽认卡作为卡片数组中的一个对象,例如带有一个 id

[{id: 218, question: "who won the NBA finals in 2020", answer: "LA Lakers"}]

同时创建一个新的闪存卡元素并将其附加到闪存卡 div。通过单击新创建的抽认卡中的删除按钮,特定元素将从本地存储和 HTML 视图中删除。

我曾尝试遍历存储中的卡片数组和 html 中的卡片数组并比较 id,但我确信有一种更简单的方法可以通过单击特定卡片的按钮来删除和编辑特定卡片。我在从外部函数调用新创建元素的元素时遇到问题。

const inputQ = document.querySelector('#input-question')
const inputA = document.querySelector('#input-answer')
const flashCards = document.querySelector('.flash-cards')
const mainCard = document.querySelector('.container')
// btns
const btnAdd = document.querySelector('.add')
const btnClose = document.querySelector('.close')
const btnSave = document.querySelector('.save')



//  open main card
btnAdd.addEventListener('click', (e) => {
  e.preventDefault()
  mainCard.classList.remove('hide')
  mainCard.classList.add('show-card')
})
// close Main Card
btnClose.addEventListener('click', () => {
  mainCard.classList.remove('show-card')
  mainCard.classList.add('hide')
})



function save() {
  if (inputQ.value === '' || inputA.value === '') {
    return false

  } else {
    const id = Math.floor(100 + Math.random() * 900)
    // parse var as an empty cards
    const cards = JSON.parse(localStorage.getItem('cards')) || [];
    // // create new obj from input fields
    const card = {
      id,
      question: inputQ.value,
      answer: inputA.value,
    }
    // push new obj to cards (empty or full)
    cards.push(card);
    // convert cards to string and store in local storage
    localStorage.setItem('cards', JSON.stringify(cards));
    inputQ.value = ""
    inputA.value = ""
    // *** Do not clear the input values here! 
    // or else we will be adding empty strings when we create the new element
    // from another module addCard
  }



}


// https://stackoverflow.com/questions/42219531/how-to-retrieve-data-from-local-storage

function view() {
  if (localStorage.getItem('cards') != null) {
    let cards = JSON.parse(localStorage.getItem('cards'))
    for (let i = 0; i < cards.length; i++) {
      const card = cards[i];
      let newCard = document.createElement('div')

      newCard.className = 'new-card'
      newCard.innerHTML = `
            <p class="card-id hide">${card.id}</p>  
            <p>${card.question}</p>
            <button class="btn show">Show/Hide</button> 
            <p>${card.answer}</p>
            <button class="btn edit">Edit</button>  
            <button onclick= "remove()" class="btn delete">Delete</button>
            `
      flashCards.appendChild(newCard)

    }

  }
}

function remove() {
  let cards = JSON.parse(localStorage.getItem('cards'))
  let cardId = document.querySelector('.card-id')

}

function edit() {

}


btnSave.addEventListener('click', () => {
  save()
  view()
})




//  display cards when loading page (refresh)
window.addEventListener('DOMContentLoaded', () => {
  view()
});

标签: javascripthtmllocal-storage

解决方案


假设您的 id 是唯一的...考虑将您的本地存储 json 字符串编码为对象对象,而不是对象数组,其中卡 ID 构成键...

{
  '218':{id: 218, question: "who won the NBA finals in 2020", answer: "LA Lakers"},
  '219':{id: 219, question: "who was the 1st president", answer: "George Washington"}
}

这将允许您通过引用 id 从对象中轻松添加/删除新卡片,因为它将成为键。

您还需要更新循环的代码,例如您的视图函数:

function view() {
  if (localStorage.getItem('cards') != null) {
    let cards = JSON.parse(localStorage.getItem('cards'))
    let cardKeys = Object.keys(cards);
    cardKeys.forEach(key => {
      const card = cards[key];
      let newCard = document.createElement('div')
      newCard.className = 'new-card'
      newCard.innerHTML = `
            <p class="card-id hide">${card.id}</p>  
            <p>${card.question}</p>
            <button class="btn show">Show/Hide</button> 
            <p>${card.answer}</p>
            <button class="btn edit">Edit</button>  
            <button onclick= "remove()" class="btn delete">Delete</button>
            `
      flashCards.appendChild(newCard)
    });
  }
}

推荐阅读