2011-10-16 26 views
1

好的, 所以我使用jquery创建了一个cookie并在其中存储了一个div。 这个div有很多格式化,其他divs,文本等等。使用jQuery存储和检索cookie中的div

var rentContainer = document.createElement('div'); 
rentContainer.setAttribute("class","module"); 
var carContainer = document.createElement('div'); 
carContainer.setAttribute("class","carRentContainer"); 
rentContainer.appendChild(carContainer); 
.... and a lot of other things go in this rentContainer div 

现在保存在cookie的

$.cookie('rented_car', rentContainer); 

万物看起来不错高达现在。

当页面刷新和正文加载时,现在是时候得到这个div并在页面上显示它(具有相同的格式,结构等)。

所以在我的功能我有

var rented_car_cookie = $.cookie("rented_car"); 
if(rented_car_cookie){ 
    document.getElementById('rentit').appendChild(rented_car_cookie); 
    //rentit is already defined and exists on the page. All I need is to add the cookie div content on it. 

,但是这给了我一个错误信息

Firebug的日志已经达到极限。 0个条目未显示。首选项
未捕获异常:[Exception ...“无法转换JavaScript参数arg 0 [nsIDOMHTMLDivElement.appendChild]”nsresult:“0x80570009(NS_ERROR_XPC_BAD_CONVERT_JS)”location:“JS frame :: iGo.js :: checkCookies :: line 10 “data:no]

请帮忙。做这个的最好方式是什么?

回答

4

无论如何,在cookie中存储完整的html元素是件坏事。也许最好使用JSON。

无论如何,你可以尝试在cookie中保存div作为html字符串。

// set 
$.cookie("rented_car", $(rentContainer).html()) 

// get 
var content = $.cookie("rented_car"); 
var $rentContainer = $('<div class="module">' + content + '</div>'); 

代码:http://jsfiddle.net/yecf8/

但是你要知道,有很多的了解有关的cookie不同的浏览器不同的限制。例如:

的Microsoft Internet Explorer以下RFC符合2109建议的最低限制:

  • 至少300饼干每个Cookie
  • 至少4096字节(如由字符的大小测量在Set-Cookie标头的语法描述中包括cookie非终端)
  • 每个唯一的主机或域名至少有20个饼干
+0

感谢您的帮助 – kk1957