繁体   English   中英

我想使用该功能从本地存储密钥中删除项目

[英]I want to remove item from local storage key with the function

function remove(current) {

    let text = "Are You Sure ?";


    if (confirm(text) == true) {
        current.parentElement.parentElement.remove();
        // document.getElementById("tablebody1").deleteRow(element.parentNode.rowIndex);
        text33 = JSON.parse(localStorage.getItem("storex"))

        function rem(arr, index) {
            return arr.filter(function(ele) {
                return ele != index
            })
        }

        localStorage.setItem('text32', JSON.stringify(result));
        localStorage.getItem("text32")
    }
}

我正在尝试从本地存储中删除项目我在屏幕上呈现表数据,但我的表数据正在进入本地存储我想删除特定项目,例如:

如果我有这样的本地存储

0: {namex: "ANUJ", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
1: {namex: "ANUJ", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
2: {namex: "ANUJ", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
3: {namex: "ANUJ", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
4: {namex: "ANUJ", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
5: {namex: "ANUJ", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
6: {namex: "rohit", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}

假设我要删除 6 个项目。 我该怎么做,或者如果我在刷新页面时将其删除,它会再次出现

您可以使用此方法删除localstorage项目:

 //setting item localStorage.setItem('image', 'myCat.png'); //removing item localStorage.removeItem('image');

    function example(){

  let array = [
    {namex: "1", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}, 
    {namex: "2", lnamex: "ANUJ", emailx: "anuj123@gmail.com"},
    {namex: "3", lnamex: "ANUJ", emailx: "anuj123@gmail.com"},
    {namex: "4", lnamex: "ANUJ", emailx: "anuj123@gmail.com"},
    {namex: "5", lnamex: "ANUJ", emailx: "anuj123@gmail.com"},
    {namex: "6", lnamex: "ANUJ", emailx: "anuj123@gmail.com"}
  ];
  
        localStorage.setItem('text32', JSON.stringify(array));
        
        let getDataFromLocalStorage = JSON.parse(localStorage.getItem("text32")); //convert your saved string array to object
        
        let result = getDataFromLocalStorage.filter((x, idx) => idx != 1);

        document.getElementById('ex').innerHTML = JSON.stringify(result)
}

您必须将数组保存为本地存储中的字符串,因此您必须将其取回并将其转换为 Object 并使用filter()方法。 根据上面的例子,它将给出除第一个索引对象之外的所有数据

如果要删除第 6 个,则必须将索引号发送为 5,因为数组对象从第 0 个索引开始

然后如果需要,将其作为字符串保存回本地存储

这是 JsFiddle

暂无
暂无

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

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