如何根据分配给当前单击元素的数据从 localStorage 中删除 JSON 对象?

How do I delete a JSON object from localStorage, according to data assigned to currently clicked element?

场景

json数据:

 Object {
    sess_id   : 182104, 
    name      : "AUTOMECH FORMULA", 
    city      : "Cairo", 
    country   : "Egypt", 
    event_url : "automech-formula"
}

events:189 Object {
    sess_id   : 182104, 
    name      : "AUTOMECH FORMULA", 
    city      : "Cairo", 
    country   : "Egypt", 
    event_url : "automech-formula"
}

快照(对于在特定 div 单击时删除的所有数据):-

HTML:

<div class="evt_date"  style="overflow:hidden" style="overflow:hidden" itemscope itemtype="http://schema.org/Event">                             
    <a href="javascript:void(0);"  class="favourate_dextop" id="fav'.$data[$k]['id'].'"  onClick=" favaorite('.$data[$k]['id'].',\''.$name_event.'\',\''.$event_city.'\',\''.$event_country.'\',\''.$event_urls.'\',this)"></a>
</div>

Javascript:

var image2 = 'http://im.gifbt.com/images/star1_phonehover.png';
var image1 = 'http://im.gifbt.com/images/star1_phone.png';
var toggle = 1;

function favaorite(sess_id,name,city,country,event_url,pointer){
    var eventData;
    //is anything in localstorage?
    if (localStorage.getItem('eventData') === null) {
        eventData = [];
    }else{
        // Parse the serialized data back into an array of objects
        eventData = JSON.parse(localStorage.getItem('eventData'));
        console.log(eventData);   
    }
    var details={};
    details.sess_id   = sess_id;
    details.name      = name;
    details.city      = city;
    details.country   = country;
    details.event_url = event_url;

    // Push the new data (whether it be an object or anything else) onto the array
    eventData.push(details);

    if (toggle == 1){
        console.log("1");
        $(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + image2 + '")');
        toggle = 0;
    }else{
        console.log("2");
        $(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + image1 + '")');
        $.each(eventData, function(key, value){
            console.log(value);
            //$('#fav'+ delete value.sess_id + '');
            //$('#fav'+ delete value.name + '');
            //$('#fav'+ delete value.city + '');
            //$('#fav'+ delete value.country + '');
            //$('#fav'+ delete value.event_url + '');
            delete value.sess_id;
            delete value.name;
            delete value.city;
            delete value.country;
            delete value.event_url;            
            //localStorage.removeItem(value.sess_id);

        });
        toggle = 1;
    }
    // Alert the array value
    // alert(eventData);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
    console.log(jsondata);
}

Fiddle

主要问题是您正在尝试 JSON.stringify 一个正常的 javascript 数组:

eventData = [];

虽然只有当您的数据是一个对象时才有效:eventData = {}

接下来是这样的:

delete value.sess_id;
delete value.name;
delete value.city;
delete value.country;
delete value.event_url;

通过上述操作,您实际上是在清空对象而不是删除它。因此,您的新数据看起来像:{}{}{}{}{}...(表示许多空的匿名对象)。要删除对象,首先你得知道你到底要删除哪个对象((*)见下一部分)


我的 advice/solution :

  • 我会删除 onclick 属性并改用 jQuery 的 .click() 事件处理程序。

  • 我会将所有数据保存在 data 属性中 - 这样您就可以非常轻松地将与元素关联的数据作为对象获取(无需进一步处理)。

  • 检查 toggle 状态是不必要的,因为它会在每次 单击 时自然切换。您应该只检查对象的存在并相应地 delete/insert 它。对于图像本身,使用 .toggleClass() 并使用适当的图像背景设置 CSS class(而不是以编程方式替换它)。

  • (*) 我会给 localStorage 中的每个对象一个 key,以便以后可以识别它。它可以是任何具有指定元素的独特且可识别的 ("matchable")。我将其设置为当前单击元素的 id 属性,例如:
    fav1:{name :'blah', ...}, fav2:{...}, ...

HTML:

<a href="#" class="favourate_dextop" id="fav'.$data[$k]['id'].'"
    data-sess_id="'.$data[$k]['id'].'"
    data-name="'.$name_event.'"
    data-city="'.$event_city.'"
    data-country="'.$event_country.'" 
    data-event_url="'.$event_urls.'" >
</a>

jQuery:

$(document).ready(function(){

    // declare an empty object (not array):
    var eventData = {};
    // check localStorage first after the page is ready (not on click):
    if (localStorage.getItem('eventData') !== null) {
        // if there's any faved link in the localstorage, highlight it:
        $.each(eventData = JSON.parse(localStorage.getItem('eventData')), function(id){
            $('#'+id).addClass('faved');
        });
    }

    // instead of 'onclick' attribute, use jQuery .click() event handler:
    $('.favourate_dextop').click(function(e){
        // prevent default link click (instead of using "javascript:void(0);" in a href attribute):
        e.preventDefault();
        // check if the link "id" attribute (this.id) exists in the object:
        if (eventData[this.id] !== undefined) {
            // if so, delete it:
            delete eventData[this.id];
        }else{
            // if not, add it:
            // the .data() method gets all 'data' attributes of the element (as an objct) 
            eventData[this.id] = $(this).data();
        }
        // toggle '.faved' class:
        $(this).toggleClass('faved');
        // update localstorage:
        localStorage.setItem('eventData', JSON.stringify(eventData));
    });     
});

.faved class 添加到您的 CSS,而不是将图像背景替换为 jQuery:

.favourate_dextop.faved, .favourate_dextop:hover{
    background:url('http://im.gifbt.com/images/star1_phonehover.png') no-repeat;
}

JSFiddle