2013-01-14 227 views
3

我有一個窗體,當點擊一個按鈕時,新的輸入被追加。 一切工作服從正確的時候,但如果我打回瀏覽器的所有附加字段都丟失了..jQuery的追加歷史記錄後返回瀏覽器

有沒有打這個瀏覽器的按鈕時,以維護它們的方法嗎?

謝謝!

+0

您必須使用會話或cookie。 – sp00m

回答

1

您的附加元素只存在於未被任何瀏覽器緩存的DOM中。

我建議你使用cookies來解決這個問題,請https://github.com/carhartl/jquery-cookie

要追加東西,這樣的餅乾

$.cookie("row", "a new row or whatever"); 

// or preferably a json 
var myJsonRow = { 
    row: 1, 
    value: "Test" 
} 
$.cookie("row", JSON.stringify(myJsonRow)); 

要閱讀這個非常簡單的餅乾簡單地使用

$.cookie("row"); 

現在顯然你需要比這更先進的東西,但這可以在json對象中處理。

開始通過創建一個JSON模式你覺得舒服,像這樣

// Basic row-pattern 
var cookieRows = { 
    rows: [ 
     { 
     value: "row 1", 
     type: "radio" 
     }, 
     { 
     value: "row 2", 
     type: "text" 
     }, 
     { 
     value: "row 3", 
     type: "password" 
     }, 
    ] 
} 

並實行

$(document).ready(function(){ 
    // Test if the cookie is set 
    if(!$.cookie("rows")) { 

     var cookieRows = { 
     rows: [] 
     } 

     // Register the pattern 
     $.cookie("rows", JSON.stringify(cookieRows)); 
    } 

    // Adding rows 

    // Register your event handler 
    $("#control").click(function(){ 

     // Get the control element 
     var controlElement = $(this); 

     // Fetch the needed information and create a row 
     var cookieRow = { 
     value: controlElement.val(), 
     type: controlElement.attr('type') 
     } 

     // Get the cookie 
     var cookieRows = JSON.parse($.cookie("rows")); 

     // Add the value to the cookie 
     cookieRows.rows.push(cookieRow); 

     // And save the cookie 
     $.cookie("rows", JSON.stringify(cookieRows)); 
    }); 
}); 

不錯啊,你的想法!

+0

謝謝你們兩位!我開始測試會話,如果我不能讓它工作,我會嘗試用餅乾,而不是..再見! – buu