我的计划是将我的元素存储在localStorage一旦他们被阅读过一次(对于一个在线应用程序 - 我认为如果我可以让它工作,它将显着加快我的应用程序)。所以我提出了以下内容,但内容似乎要么存储要么返回为null。现在我认为一个元素基本上是一个字符串所以我不必用它做任何事情来将它存储在localStorage中,但显然不是。有谁知道它是否有可能达到我的目的?
如果您想要旋转它,那么您需要一个包含html的小文件传递给它。内容并不重要。第一次运行if (content)
将评估为false。下一次是真的,我添加了.clear()
以使其交替。第三次showSource函数将填充id=localor
元素(需要与id=content
元素或您选择填充的任何其他元素分开),在文件&"之后显示空值#34;
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");
});
请帮忙。
感谢。
答案 0 :(得分:0)
您正在做的事情不起作用的原因是您在项目加载之前保存该项目。 load
与所有(合理的)ajax调用一样,异步。当您致电load
时,开始,但稍后结束。然后你的代码继续并抓住它认为的内容并保存它,但内容还没有。
改为使用回调:
$(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.
});
但是......你还没有重新发明浏览器缓存吗?