简体   繁体   中英

Storing user highlighted rows using HTML5 localStorage

I have a javascript function that adds a table row id each time a user highlights a row to an array and then also removes that corresponding id from the array when the user unhighlights that same row.

Each row has a unique id field.

I have been trying to using localStorage to remember what row(s) the user has highlighted in the array over multiple sessions so that if they close the browser and come back later I can read from that array and automatically highlight the previously highlighted rows.

I am getting stuck on how to get the localStorage part of it to remember the array as from my reading of localStorage, it doesn't supports arrays only strings. All I need to do is store an array of numbers to read from each time I load the page.

var selectedTeams = [];
var teamIndex;

$('#leaderboard').on('click', 'tr', function() {
    if($(this).hasClass('highlight')){
          $(this).removeClass('highlight')
          teamIndex = selectedTeams.indexOf(this.getAttribute('id'))
          selectedTeams.splice(teamIndex,1)
    }
    else {
          $(this).addClass('highlight')
          selectedTeams.push(this.getAttribute('id'))
    }
});

Any suggestions on where to go from here would be appreciated.

Cheers

For a simple example, you'd do something like this (which Dave alluded to).

Assuming you have done all your checks for valid localStorage capability.

var someArray = ['<tr><td>test 3</td></tr>','<tr><td>test</td></tr>','<tr><td>test 3</td></tr>']

window.localStorage.setItem('mySavedArray',JSON.stringify(someArray));

then to get it:

JSON.parse( window.localStorage.getItem('mySavedArray') );

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