You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击删除按钮从LocalStorage删除指定表格行及存储覆盖问题求助

Hey there! Let's tackle those two issues you're facing with your joke storage project—they're common pitfalls when working with localStorage, so we'll fix them up step by step.

Core Problem with Your Current Setup

Right now, you're storing each field (joke, name, age, delete button) in separate arrays in localStorage. This makes it impossible to link a joke entry's fields together, and causes both the overwriting and mass-deletion issues. We'll restructure your data to store complete joke entries as single objects in one array, which will solve both problems.


Fix 1: Stop Overwriting Existing Data

The reason new entries overwrite old ones is because you're initializing your savedLocalStorage1 etc. arrays as empty every time the page loads, instead of pulling existing data from localStorage first. By switching to a single array of entry objects, we can fix this easily.

Fix 2: Delete Only the Targeted Entry

Once each joke entry has a unique ID and is stored as a single object, we can use that ID to find and remove only the specific entry from both the array and localStorage, instead of clearing everything.


Modified Full Code

Here's the updated code with both fixes, plus comments explaining key changes:

// Variables
const jokeInput = document.getElementById("text-1");
const nameInput = document.getElementById("text-2");
const ageInput = document.getElementById("number");
const submitBtn = document.querySelector(".btn");
const output = document.querySelector(".output-container");

// Eventlisteners
submitBtn.addEventListener("click", validateFields);
output.addEventListener("click", deleteEntry);

// Initialize our entries array with existing data from localStorage
let jokeEntries = JSON.parse(localStorage.getItem("jokeEntries")) || [];

// Error function
function showError(input) {
  const formControl = input;
  formControl.style.border = "3px solid red";
  removeStyle(formControl);
}

// Show Error message
function showErrorMessage(input, message) {
  input.classList.add("error");
  input.innerText = message;
  setTimeout(() => {
    input.classList.remove("error");
  }, 3000);
}

// Show success
function showSuccess() {
  jokeInput.style.border = "3px solid green";
  nameInput.style.border = "3px solid green";
  ageInput.style.border = "3px solid green";
  const small = document.querySelector(".small-3");
  small.classList.add("success");
  small.innerText = "You have successfully entered all fields";
  setTimeout(() => {
    small.classList.remove("success");
  }, 3000);
  removeStyle(jokeInput, nameInput, ageInput);
}

// Remove Style
function removeStyle(input, input2, input3) {
  setTimeout(() => {
    input.style.removeProperty("border");
    input2.style.removeProperty("border");
    input3.style.removeProperty("border");
  }, 3000);
}

// Main Function
function validateFields(e) {
  e.preventDefault();
  let isValid = true;

  if (jokeInput.value === "") {
    showError(jokeInput);
    const small = document.querySelector(".small-1");
    showErrorMessage(small, "Please provide a joke");
    isValid = false;
  }
  if (nameInput.value === "") {
    showError(nameInput);
    const small = document.querySelector(".small-2");
    showErrorMessage(
      small,
      "Please fill in your name with alphabetical characters only"
    );
    isValid = false;
  }
  if (ageInput.value === "") {
    showError(ageInput);
    const small = document.querySelector(".small-3");
    showErrorMessage(small, "Please enter your age");
    isValid = false;
  }
  
  if (isValid) {
    showSuccess();
    // Create a new entry object with unique ID and all fields
    const newEntry = {
      id: uuidv4(), // Use your existing UUID generator here
      joke: jokeInput.value,
      name: nameInput.value,
      age: ageInput.value
    };
    addEntryToDOM(newEntry);
    updateLocalStorage();
    // Clear inputs after submission
    jokeInput.value = "";
    nameInput.value = "";
    ageInput.value = "";
  }
}

// Add a single entry to the DOM
function addEntryToDOM(entry) {
  const outputContainer = document.querySelector(".output-container");
  const row = outputContainer.insertRow(1);
  // Store the entry ID in the row's dataset for later deletion
  row.dataset.entryId = entry.id;
  
  const cell1 = row.insertCell(0);
  const cell2 = row.insertCell(1);
  const cell3 = row.insertCell(2);
  const cell4 = row.insertCell(3);
  
  cell1.innerHTML = entry.joke;
  cell2.innerHTML = entry.name;
  cell3.innerHTML = entry.age;
  cell4.innerHTML = `<i class="fas fa-trash-alt"></i>`;
  
  // Add the new entry to our array
  jokeEntries.push(entry);
  
  if (outputContainer.querySelectorAll("tr").length > 2) {
    resetBounce();
  }
}

// Update localStorage with our current entries array
function updateLocalStorage() {
  localStorage.setItem("jokeEntries", JSON.stringify(jokeEntries));
}

// Load existing entries from localStorage on page load
window.onload = () => {
  jokeEntries.forEach(entry => {
    addEntryToDOM(entry);
  });
};

// Reset bounce function (unchanged)
function resetBounce() {
  setTimeout(() => {
    const cell4 = document.querySelectorAll(".fas");
    cell4.forEach((element) => element.classList.remove("fas", "fa-trash-alt"));
  }, 50);
  setTimeout(() => {
    const cell4 = document.querySelectorAll(".fas");
    cell4.forEach((element) => element.classList.add("fas", "fa-trash-alt"));
  }, 75);
}

// Delete specific entry from DOM and localStorage
function deleteEntry(e) {
  if (e.target.className.includes("fas")) {
    const row = e.target.parentElement.parentElement;
    const entryId = row.dataset.entryId;
    
    // Remove the row from DOM
    row.remove();
    
    // Filter out the entry with matching ID from our array
    jokeEntries = jokeEntries.filter(entry => entry.id !== entryId);
    
    // Update localStorage with the filtered array
    updateLocalStorage();
  }
}

Key Changes Explained

  1. Single Array for Entries: We now use jokeEntries to store complete joke objects (each with id, joke, name, age). This links all fields of a single entry together.
  2. Initialize from localStorage: On page load, we pull existing data from localStorage into jokeEntries (or start with an empty array if nothing exists).
  3. Store ID in DOM Rows: Each table row has a data-entry-id attribute matching the entry's UUID, so we can identify which entry to delete when the trash button is clicked.
  4. Targeted Deletion: When deleting, we filter the jokeEntries array to remove only the entry with the matching ID, then update localStorage with the new array.
  5. Prevent Overwriting: Since we're pushing new entries to the existing array (instead of starting fresh each time), old data stays intact when adding new entries.

This should fix both your issues completely! Let me know if you need clarification on any part.

内容的提问来源于stack exchange,提问作者Daniel Persson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:27:31