问题
My plan is to store my elements in localStorage once they've been read once (for an online app – I figure that if I can get it to work it will speed up my app significantly). So I came up with the following, but the contents seem to either be stored or come back as null. Now I thought that an element was fundamentally a string so I wouldn't have to do anything with it to store it in localStorage, but apparently not. Does anyone know if it's possible to achieve what I want?
If you want to take it for a spin then you'll need a small file holding html to pass to it. The contents aren't important. The first time it runs if (content)
will evaluate to false. The next time true and I added the .clear()
to make it alternate. The third time the showSource function will populate the id=localor
element (which will need to be separate from the id=content
element or whatever other element you choose to populate) showing the null after "from File ".
function showSource(source) { //Function and related element only here for testing
$("#localor").html("<p>"+source+"</p>");
}
//local is the name of the localStorage element
//id is the id of the element in the main form
//source is where the content for the element originates.
function loadElement(local, id, source) {
//This is the generic script for attempts to load an element.
content = localStorage.getItem(local); //Try to load from local storage
if (content) {//If found
$(id).html(content);
showSource("from Local " + content); //Added only for testing
localStorage.clear(); //Added only for testing
//load into the #content element
} else {//Not found
$(id).load(source);
showSource("from File " + content); //Added only for testing
//so load it from the server..
localStorage.setItem(local,$(id).html());
//then save it to the local storage, so we don't have to do this again any time soon.
}
}
$(document).ready(function() {
loadElement("login.1001", "#content", "login.html");
});
Please help.
Thanks.
回答1:
The reason what you're doing doesn't work is that you're saving the item before it's loaded. load
works asynchronously, like all (reasonable) ajax calls. The process starts when you call load
, but finishes later. Your code is then continuing and grabbing what it thinks is the content and saving it, but the content isn't there yet.
Use the callback instead:
$(id).load(source, function() {
showSource("from File " + content); //Added only for testing
//so load it from the server..
localStorage.setItem(local,$(id).html());
//then save it to the local storage, so we don't have to do this again any time soon.
});
But...aren't you just reinventing the browser cache?
来源:https://stackoverflow.com/questions/24956525/how-to-convert-an-element-to-a-string-that-can-be-stored-and-restored-from-local