简体   繁体   中英

Jquery to retain the links clicked and add/remove css class after refresh

I have a page with multiple "Filters" which are basically links. Upon clicking the link, I am able to filter the results. However, I would like to add/remove class upon refresh of page when the link is clicked. I tried using localstorage but my localStorage returns null. Any help would be appreciated. I am very new to Jquery. It is probably a repeat but my situation seems to be unique as localstorage on refresh is returning null on console.

if (localStorage.getItem('filters')==null){
var filters={};
alert("in here");
}
else{
filters= JSON.parse(localStorage.getItem('filters'));
}

$(".li-filter").click(function(){

/*event.preventDefault();*/
var idstr= this.id.toString();
/*console.log(idstr);*/
if (filters[idstr] != undefined){
  filters[idstr] = filters[idstr]  +1;
}
else {
  filters[idstr]  = 1;
}
localStorage.setItem('filters',JSON.stringify(filters));
console.log(filters);
});

I am not sure if I need to use AJAX to retain my selected link ids.

I have a working fiddle based off of your description here : https://jsfiddle.net/7mtxw2a3/4/ . I'd suggest making use of your browser's developer tools to verify the contents of your local storage after setting a value and then again on page refresh.

$(document).ready(function() {
  var cached = localStorage.getItem('filters');
  var filters = cached ? JSON.parse(cached) : {};
  for (id in filters) {
    $('#' + id).addClass('cached');
  }
  $('li').click(function() {
    $(this).addClass('cached');
    var id = this.id.toString();
    if (filters[id]) {
        filters[id] += 1;
    } else {
        filters[id] = 1;
    }
    localStorage.setItem('filters', JSON.stringify(filters));
  });
});

I modified the other answer until it appeared to be working.

$(document).ready(function() {
  var cached = localStorage.getItem('filters');
  var filters = (cached) ? JSON.parse(cached) : {};
  for (id in filters) {
    $('#' + id).addClass('cached');
  }
  $('li').click(function(e) {
    $(e.target).addClass('cached');
    var id = $(e.target).attr('id').toString();
    if (filters[id]) {
        filters[id] += 1;
    } else {
        filters[id] = 1;
    }
    localStorage.setItem('filters', JSON.stringify(filters));
  });
});

The place to get your clicked object is e.target . Here's a link to the anatomy of a Jquery event object .

However, when using JQuery and events together, there are a lot of situations where you will need to feed an element back into the selector as I've done with $(e.target) .

And to ask for the id attribute, you need then to chain the .attr() method .

Hat tip to @Freddy for getting the fiddle started. Here's my version of the fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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