如何保留数组的所有值?

时间:2017-03-24 13:54:11

标签: javascript jquery html arrays local-storage

这是我的代码:

CSS:

li{
  cursor: pointer;
}

 li:hover{
    background-color: #eee;
 }

HTML:

<ul>
  <li><a href='#1'>first post</a></li>
  <li><a href='#2'>second post</a></li>
  <li><a href='#3'>third post</a></li>
</ul>

JS:

var seen = [];
$('li').on('click', function(){
$(this).css('background-color','pink');
// storing into localstorage
if (typeof(Storage) !== "undefined") {
    if(!seen.includes($(this).find('a').attr('href'))){
        seen.push($(this).find('a').attr('href'));
        // Set to localStorage
        localStorage.setItem('seen', JSON.stringify(seen));
    }
  }
});

var seenAlready = JSON.parse(localStorage.getItem('seen'));
$.each(seenAlready,function(index, value){
   $("a[href="+'"'+value+'"'+"]").parent().css('background-color','pink');
});

正如您在this fiddle中看到的那样,粉红色将仅为一个元素(重新加载页面后)进行重新调整。也如您所知,这是因为这一行:

var seen = [];

如何处理此问题并保留该数组的所有值?

0 个答案:

没有答案