简体   繁体   English

如何从 JavaScript 中的 LocalStorage 和更新 UI 中删除数组项?

[英]How to delete array item from LocalStorage and Update UI in JavaScript?

So I have an array in my localStorage, what I want to do is give the user the ability to remove items from this array.所以我的 localStorage 中有一个数组,我想做的是让用户能够从这个数组中删除项目。 I have made changes to the UI based on event.target.parentNode .我已经基于event.target.parentNode对 UI 进行了更改。 But I want to remove the individual items based on their index from localStorage.但我想根据它们的索引从 localStorage 中删除单个项目。 Do I need to use indexOf or forEach .我需要使用indexOf还是forEach My current code does not work, I don't think I have to split the array, so I can access individual items as it is already an array?我当前的代码不起作用,我认为我不必拆分数组,所以我可以访问单个项目,因为它已经是一个数组? the function is below - any idea's? function 在下面-有什么想法吗?

function removeItemsLocalStorage() {
    const listUl = domElements.app.querySelector('.saveUl');
    listUl.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {

          // below tis to remove the element from the DOM, works ok.
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);

          //The code below seems abit iffy to me? as its here I am trying to remove from the index of the array
          let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
          let ele = displayItems.split(",");
          var index = ele.indexOf(1);
          ele.splice(index, 1);
        }
    });
}

localstorage array is like:本地存储数组就像:

["Monday", "Tuesday", "Wednesday"]

Saving to localStorage保存到本地存储

function saveItems(ele) {
    localStorage.setItem('Shopping List', JSON.stringify(ele));
    let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
    domElements.saveList.innerHTML = displayArray(displayItems);
}

saveButton.addEventListener('click', function () {
        saveItems(data);
    });

Error when clicking on the removeItemsLocalStorage() function:单击removeItemsLocalStorage() function 时出错:

Uncaught TypeError: displayItems.split is not a function

You can simply delete stuff from local storage by doing:您可以通过执行以下操作简单地从本地存储中删除内容:

  localStorage.removeItem('Shopping List');

So what you should do is getting the name of the item you want to delete and pass it to the removeItem function from localStorage.所以你应该做的是获取你要删除的项目的名称,并将其从localStorage传递给removeItem function。 You should not have to loop over the localStorage to remove it by index.您不必遍历 localStorage 以按索引将其删除。

Since in your case the "Shopping List" is an object, the common approach to solve this is by doing splicing it by the index and setting the item again.由于在您的情况下,“购物清单”是 object,因此解决此问题的常用方法是通过索引将其拼接并再次设置项目。

list.splice(index, 1);
localStorage.setItem('Shopping List', JSON.stringify(list));
let displayItems = JSON.parse(localStorage.getItem("Shopping List"));

Here you are fetching the "Shopping List" item from your local storage, and storing its content inside your displayItems variable.在这里,您从本地存储中获取“购物清单”项目,并将其内容存储在displayItems变量中。

let ele = displayItems.split(",");
var index = ele.indexOf(1);
ele.splice(index, 1);

Now your local variable ele contains your updated array.现在您的局部变量ele包含您更新的数组。 But in your localStorage, nothing has changed, and the "Shopping List" is still the same.但是在你的localStorage中,什么都没有改变,“购物清单”还是一样的。 You need to update that value, for example by doing:您需要更新该值,例如通过执行以下操作:

var newShoppingList = ele.join(',');
localStorage.setItem('shoppingList', newShoppingList);

If you are storing the value ',' seperated but as a string in local storage, then you have to use split function.如果您将值“,”分隔但作为字符串存储在本地存储中,则必须使用split function。 This would convert your string into an array.这会将您的字符串转换为数组。

There is nothing wrong in doing this.这样做并没有错。 According to me this is the optimal way for doing this.在我看来,这是做到这一点的最佳方式。

Once you get the list you can use filter method to the array to remove the unwanted element from the list.获得列表后,您可以对数组使用filter方法从列表中删除不需要的元素。

Edited:编辑:

If it is already stored as array, than you are not required to use split method at all.如果它已经存储为数组,则根本不需要使用 split 方法。 Already you have the array.你已经有了数组。 Directly use the splice method to remove the element.直接使用拼接方法移除元素。 And as you mentioned you need to remove the element by its index, Then just use正如您所提到的,您需要按其索引删除元素,然后只需使用

array.splice(index,1)

This index would have your desired index.该索引将具有您想要的索引。

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

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