Question

I have an application that reads the items stored in the localStorage and displays it in a <li /> when the page "loads".

The listview contains a split button that when pressed it removes the related item from the list; this is part of what I'm aiming for, looking around on the internet I have tried to find a way so this "delete/remove" function ALSO removes the selected item inside the <li /> from the localStorage, but for some reason my script below seems to remove random items.

$(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');
    });

I believe it has to do with the key being the wrong one but can't work my head around a way to make the script take the right key from the selected item. Or if there is a way to remove the item by taking the value alone? (Doubt it as all I find can only be done by manipulating the key).

Please any suggestions will be greatly appreciated.

Était-ce utile?

La solution

Store your key in an attribute of the anchor tag

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

and in click event refer that attribute

$('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');
});

hope this solves your problem.

Autres conseils

you should get key value , where you are performing click event on ui. let say every li is like

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

// key refrence to the name of key in localstorage and when clicking on function you can get the key value like

var key = $(this).closest().attr("data");
localStorage.removeItem(key);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top