从本地存储中删除动态显示在 <li> 中的项目

Remove item from localStorage that's dynamically displayed in a <li>

本文关键字:li 项目 存储 删除 动态显示      更新时间:2023-09-26

>我有一个应用程序,它可以读取存储在localStorage中的项目,并在页面"加载"时将其显示在<li />中。

listview包含一个拆分按钮,按下该按钮时,它会从列表中删除相关项目;这是我目标的一部分,在互联网上环顾四周,我试图找到一种方法,所以这个"删除/删除"功能也会从localStorage中删除<li />内的选定项目,但由于某种原因,我下面的脚本似乎删除了随机项目。

$(document).ready(function () {
        window.addEventListener('load', OnStorage, false);
    });
    function OnStorage(event) {
        if (window.localStorage) {
            var key, value;
            // loop through local storage
            for (var i = 0; i < localStorage.length; i++) {
                // retrieve the key
                key = localStorage.key(i);
                // set the field from the key
                value = localStorage.getItem(key);
                $("#medListDiv").show();
                var text = '<a href="#"><h2>' + value + '</h2>' + '<a href="#" class="del">Delete</a></a>';
                $('<li />', {
                html: text
                }).appendTo('ul.medList');                  
            }
            $('ul.medList').listview('refresh')
        }
    }
    //Deletes items from the medicine List
    $('ul').on('click', '.del', function (el) {
        $(this).closest('li').remove();
        localStorage.removeItem(key); //Where problem relies
        $('ul.medList').listview('refresh');
    });

我相信这与key是错误的有关,但我无法解决使脚本从所选项目中获取正确键的方法。或者是否有办法通过单独取值来删除项目?(怀疑它,因为我发现的所有内容只能通过操纵密钥来完成)。

请任何建议将不胜感激。

将密钥存储在锚标记的属性中

     var text = '<a href="#"><h2>' + value + '</h2>' + '<a href="#" key="'+key+'" class="del">Delete</a></a>';
            $('<li />', {
            html: text
            }).appendTo('ul.medList'); 

并在单击事件中引用该属性

$('ul').on('click', '.del', function (el) {
    $(this).closest('li').remove();
    var key = $(this).attr('key');
    localStorage.removeItem(key); //Where problem relies
    $('ul.medList').listview('refresh');
});

希望这能解决你的问题。

你应该得到键值,你在UI上执行点击事件。说每一个李都像

<li data='key'>....</li>

对本地存储中密钥名称的键引用 单击函数时,您可以获得键值,例如

var key = $(this).closest().attr("data");
localStorage.removeItem(key);