简体   繁体   English

使用HTML5 localStorage存储用户突出显示的行

[英]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. 我有一个javascript函数,每次用户将一行突出显示到数组时都会添加一个表行ID,然后当用户取消突出显示同一行时,也会从数组中删除相应的ID。

Each row has a unique id field. 每行都有一个唯一的ID字段。

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. 我一直在尝试使用localStorage来记住用户在多个会话中在数组中突出显示了哪些行,以便如果他们关闭浏览器并稍后返回,我可以从该数组中读取并自动突出显示先前突出显示的行。

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. 从我对localStorage的阅读中,我陷入了如何获取它的localStorage部分来记住数组的问题,它不仅支持字符串数组。 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). 对于一个简单的示例,您将执行类似的操作(Dave提到了)。

Assuming you have done all your checks for valid localStorage capability. 假设您已经对所有有效的localStorage功能进行了检查。

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') );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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