繁体   English   中英

单击删除按钮时从本地存储中删除特定表行

[英]Removing specific table Row from local storage when clicking a delete button

我对编程很陌生(只有几个星期),并且正在尝试做一个小型练习项目,您可以在其中创建笑话,然后将它们与您的姓名和年龄一起存储在本地存储中。 右侧还有一个垃圾桶,您可以在其中删除笑话。

您可以在此处查看该站点: https://nostalgic-poitras-17b692.netlify.app/

在这里您可以找到文件: https://github.com/Dannus90/JavaScript_Practise_Own_Project_Unfinished

到目前为止,您可以输入所有内容,它会检测您是否已输入。 然后笑话被存储在本地存储中并显示在表格的屏幕上。

目前有两个问题: - 如果我点击任何垃圾桶,它会从本地存储中删除所有行,我知道它为什么在代码中这样做,但我不知道如何定位特定行并且只从本地删除该行当我点击垃圾桶时存储。

  • 第二个问题是,当我做了 2 个笑话然后刷新页面时。 他们还在那里,所以一切正常。 但是,如果我在刷新后输入新的笑话,它们会覆盖旧的本地存储而不是添加到它,所以如果我再次刷新,只会显示最近的笑话。

问题应该在以下图片中找到:问题1问题2

这是我到目前为止的代码(在 GitHub 的文档中,您还可以看到随机 ID 生成器。把它拿走以减少混乱:-)):

// 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);

// Error
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();

  if (jokeInput.value === "") {
    showError(jokeInput);
    const small = document.querySelector(".small-1");
    showErrorMessage(small, "Please provide a joke");
  }

  if (nameInput.value === "") {
    showError(nameInput);
    const small = document.querySelector(".small-2");
    showErrorMessage(
      small,
      "Please fill in your name with alpabetical characters only"
    );
  }

  if (ageInput.value === "") {
    showError(ageInput);
    const small = document.querySelector(".small-3");
    showErrorMessage(small, "Please enter your age");
  }

  if (
    jokeInput.value !== "" &&
    nameInput.value !== "" &&
    ageInput.value !== ""
  ) {
    showSuccess();
    updateDOM(jokeInput.value, nameInput.value, ageInput.value);
  }
}

// Save DOM Data
let savedLocalStorage1 = [];
let savedLocalStorage2 = [];
let savedLocalStorage3 = [];
let savedLocalStorage4 = [];

// Update local storage

function updateLocalStorage() {
  localStorage.setItem(
    "savedLocalStorage1",
    JSON.stringify(savedLocalStorage1)
  );
  localStorage.setItem(
    "savedLocalStorage2",
    JSON.stringify(savedLocalStorage2)
  );
  localStorage.setItem(
    "savedLocalStorage3",
    JSON.stringify(savedLocalStorage3)
  );
  localStorage.setItem(
    "savedLocalStorage4",
    JSON.stringify(savedLocalStorage4)
  );
}

// Update DOM
function updateDOM(input1, input2, input3) {
  const outputContainer = document.querySelector(".output-container");

  const row = outputContainer.insertRow(1);
  const cell1 = row.insertCell(0);
  const cell2 = row.insertCell(1);
  const cell3 = row.insertCell(2);
  const cell4 = row.insertCell(3);

  cell1.innerHTML = `${input1}`;
  cell2.innerHTML = `${input2}`;
  cell3.innerHTML = `${input3}`;
  cell4.innerHTML = `<i class="fas fa-trash-alt id4"></i>`;

  savedLocalStorage1.push({ id: uuidv4(), cell_1: `${input1}` });
  savedLocalStorage2.push({ id: uuidv4(), cell_2: `${input2}` });
  savedLocalStorage3.push({ id: uuidv4(), cell_3: `${input3}` });
  savedLocalStorage4.push({
    id: uuidv4(),
    cell_4: `<i class="fas fa-trash-alt id4"></i>`,
  });

  updateLocalStorage();

  const rows = document.querySelectorAll("tr");
  if (rows.length > 2) {
    resetBounce();
  }
}

window.onload = (e) => {
  function DOMOutput() {
    const sto1 = JSON.parse(localStorage.getItem("savedLocalStorage1"));
    const sto2 = JSON.parse(localStorage.getItem("savedLocalStorage2"));
    const sto3 = JSON.parse(localStorage.getItem("savedLocalStorage3"));
    const sto4 = JSON.parse(localStorage.getItem("savedLocalStorage4"));

    const outputContainer = document.querySelector(".output-container");

    for (let i = 0; i < sto1.length; i++) {
      const row = outputContainer.insertRow(1);

      const cell1 = row.insertCell(0);
      cell1.innerHTML = sto1[i].cell_1;

      const cell2 = row.insertCell(1);
      cell2.innerHTML = sto2[i].cell_2;

      const cell3 = row.insertCell(2);
      cell3.innerHTML = sto3[i].cell_3;

      const cell4 = row.insertCell(3);
      cell4.innerHTML = sto4[i].cell_4;

    }
  }

  DOMOutput();
};

// Delete from local Storage

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

  setTimeout(() => {
    const cell4 = document.querySelectorAll(".id4");
    console.log(cell4);
    cell4.forEach((element) => element.classList.add("fas", "fa-trash-alt"));
  }, 75);
}

// Delete Function
output.addEventListener("click", function clearRow(e) {
  if (e.target.className.includes("fas")) {
    e.target.parentElement.parentElement.remove();

    // Needs to be fixed!

    localStorage.removeItem("savedLocalStorage1");
    localStorage.removeItem("savedLocalStorage2");
    localStorage.removeItem("savedLocalStorage3");
    localStorage.removeItem("savedLocalStorage4");
  }
});

您的问题 - 正如您正确意识到的那样 - 是您删除了整个项目。 但是您需要做的是从旧输入中复制内容并在其上添加新内容。

第一步是声明let sto1, sto2, sto3, sto4; 作为全局变量,以便您的每个函数始终可以访问它。 你在你的 onload function 中填充这些变量,基本上和你之前做的一样,你只需要删除它们前面的 const 关键字。

当您将新项目添加到本地存储时,您将访问全局存储变量并使用扩展运算符将所有旧项目添加到新创建的数组中:

 savedLocalStorage1 = [...sto1, { id: uuidv4(), cell_1: `${input1}` }];
  savedLocalStorage2 = [...sto2, { id: uuidv4(), cell_2: `${input2}` }];
  savedLocalStorage3 = [...sto3, { id: uuidv4(), cell_3: `${input3}` }];
  savedLocalStorage4 = [
    ...sto4,
    {
      id: uuidv4(),
      cell_4: `<i class="fas fa-trash-alt id4"></i>`
    }
  ];

对于删除一个项目,你基本上做同样的事情,但你必须删除你不再需要的项目,也许使用过滤器 function (单独做这个练习,询问你是否需要提示)。

感谢帮助!

它没有完全工作,但它让我知道该怎么做。 如您所说,我首先将 sto 设置为全局变量,但我无法在 savedLocalStorage 上使用传播它给了我以下消息:在此处输入图像描述

垃圾桶也开始不同步。

不知道为什么它没有按预期工作,因为我认为解决方案看起来不错。 当我在 window 加载时仅将其存储在 sto1、sto2、sto3、sto4 中时,savedLocalStorage 的长度可能不能是 null。

我在这里使用了扩展运算符,然后它似乎可以工作(也将 sto1-2-3-4 初始化为空 arrays - 这也可能是一个问题):

暂无
暂无

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

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