如何获得<a> element stored in localstorage

时间:2018-10-24 06:17:03

标签: jquery onload

I'm storing an <a> element in localstorage and trying to get it back in a function which runs on window.onload event. Problem is, after storing that element I get [object Object] and when I apply jquery on it, it throws exception. I'm trying to get its parent here. Could anybody help me My code:-

$('a').on('click', function(){
  localStorage.setItem('link', $(this));
})
window.onload=function(){
  var link = localStorage.getItem('link'); //gives [object Object]
  var parent = $(link).parent(); //got error here
}

I'm storing that link so that I could add 'active' class to it and its parent elemnt on page reload/refresh. On load I want them to be active in side menubar. my sidebar menu:-

<ul>
 <li id="1">
  <ul><li><a href="/pages/1"></a></li><li><a href="/pages/2"></a></li></ul>
 </li>
 <li id="1">
  <ul><li><a href="/pages/3"></a></li><li><a href="/pages/4"></a></li></ul>
 </li>
</ul>

1 个答案:

答案 0 :(得分:0)

您可以做的是在保存到localstorage之前将元素转换为字符串,并在从localstorage检索后将其转换回对象。

$('a').on('click', function(){
  localStorage.setItem('link', JSON.stringify(this));

  var retrievedObject = localStorage.getItem('link');

  //do anything with the object from localstorage
  console.log(JSON.parse(retrievedObject));
});

或者您可能想要另一种方法。例如,您可以将单击的a元素的索引存储在localstorage中,并像下面的笔一样在pageload上重建它

https://codepen.io/niklasp-the-looper/pen/Xxxyay?editors=1010

$('ul a').each(function(idx, element) {
  $(element).on('click', function() {
    localStorage.setItem('linkIdx', idx);
  });
});

$('#get').on('click', function() {
  var linkIndex = localStorage.getItem('linkIdx');
  var element = $('a')[linkIndex];
  console.log(element);
});

希望您能明白。存储超出实际需求的存储是不明智的。除了存储具有功能的jQuery对象外,如下所述。

相关问题