2013-01-14 35 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