简体   繁体   中英

jQuery localStorage if exists save it

I'm trying to understand the localStorage method. I have this code:

player = $('#player').val();
team   = $('input[name="team"]:checked').val();

then I tried to storage it and show it even if the page is refreshed

var a = localStorage.setItem('managername', player);
var b = localStorage.setItem('managerteam', team);

$('#tournament').append(a b);

setItem does not return the value. You need to use getItem to retrieve the values after they have been saved. Also note that you need to concatenate a and b in the append (or append them separately).

// save
localStorage.setItem('managername', player);
localStorage.setItem('managerteam', team);

// retrieve
var a = localStorage.getItem('managername');
var b = localStorage.getItem('managerteam');    
$('#tournament').append(a + ' ' + b);

HTML5 gives you 2 types of storage options

  1. Local Storage - stores data with no expiration date, unless you explicitly clear it
  2. Session Storage - stores data for one session (data is lost when the tab is closed)

So if you want to persist data between page refreshes, use Local Storage . You need to check for that if your browser supports it like this

if(window.localStorage){
  // now we have local storage support
  var storage =  window.localStorage;
  storage.setItem("lastname", "Smith");
}

similarly when you wan't to retrieve do the same check

if(window.localStorage){
  // now we have local storage support
  var storage =  window.localStorage;
  var name = storage.getItem("lastname");
  console.log(name);
}

if you wan't to delete items from local storage, use removeItem('urIdentifier)

Instead of setItem() and getItem(), you can even use dot(.) notation

// store
storage.lastName = "smith";
// retrieve
alert(storage.lastName);

In case you need more details, look at this

EDIT :

$('.urAddBtn').on('click',function(){
    var player = $('#player').val(),
        team   = $('input[name="team"]:checked').val();
    if(window.localStorage){
      /* now we have local storage support in the browser
         get the local storage instance */
      var storage =  window.localStorage; 
      // save items to storage
      storage.setItem('managername', player);
      storage.setItem('managerteam', team);
    }
});

Some where else when you click on remove icon

$('.removeBtn').on('click',function(){
    if(window.localStorage){
      /* now we have local storage support in the browser
         get the local storage instance */
      var storage =  window.localStorage; 
      // remove items from local storage
      storage.removeItem('managername');
      storage.removeItem('managerteam');
    }
});

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