2014-07-25 37 views
0

我的計劃是將我的元素存儲在localStorage中,一旦它們被讀取一次(對於在線應用程序 - 我認爲如果我可以將它工作會顯着加快我的應用程序)。所以我想出了以下內容,但內容似乎要麼被存儲,要麼返回爲空。現在我認爲一個元素基本上是一個字符串,所以我不需要對它進行任何操作來將它存儲在localStorage中,但顯然不是。有誰知道是否有可能實現我想要的?如何將元素轉換爲可從localStorage存儲和恢復的字符串

如果你想把它用於旋轉,那麼你需要一個小文件來保存html傳遞給它。內容並不重要。第一次運行if (content)將評估爲false。下一次是真實的,我添加了.clear()使其交替。 ShowSource函數將第三次填充id=localor元素(它將需要與id=content元素或您選擇填充的任何其他元素分開),顯示「從文件」後的空值。

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

我相信你正在重新創建瀏覽器緩存...... –

+1

這是用調試器遍歷代碼,檢查變量和諸如你去之類的(許多)情況之一,會告訴你答案(或者至少讓你走上去)。您的瀏覽器內置了一個調試器。該調試器是你的朋友。 :-) –

+0

Firebug適用於Firefox – pheromix

回答

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. 
}); 

但是......你不只是重新發明瀏覽器緩存?

+0

據我所知,瀏覽器緩存並不是非常持久,但我認爲你是對的。謝謝你的幫助。我仍然習慣於同步運行和異步運行。 – SteveC

+0

的確,緩存循環得相當快(瀏覽器的默認緩存大小驚人地小),但我仍然只是確保您緩存友好,而不是將您的頁面存儲在本地存儲中。不僅如此,如果每個人都開始這樣做,本地存儲將開始具有相同的問題緩存。 –

+0

這絕對是一個風險。可悲的是,如果我按照建議在回調中編寫代碼(即使刪除了「內容」一詞 - 這是一個錯誤),腳本根本無法運行。我很困惑,在這些早期,這對我來說是一個頻繁的狀態。我試着將參數添加到回調函數中,但這沒有什麼區別。 – SteveC

相關問題