https://jsfiddle.net/ebo7hLo9/10/ - here's a fiddle!
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", $(id).text());
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$("a:contains('" + selectedolditem + "')").addClass("active");
}
});
Your code was having issues remembering what element to grab. I think it's due to the web storage API's unfamiliarity with objects. Instead I got the text from the element that was selected, stored it in localStorage and on page load matched it with the correct element. Also there was part of your code that was dealing with finding the class "active" within the siblings()
of the selected element and removing it. That complex of code is largely unnecessary. I replaced it with the class selector $(".active")
I didn't change this in the code, but I'd advise against using localStorage
in favor of sessionStorage
so that the storage will clear itself on tab/browser close.
For more info take a look at this previous stackoverflow post: Storing Objects in HTML5 localStorage
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…