2013-04-07 67 views
0

我正在使用jQuery来添加/删除输入字段。如何在浏览器中存储由jQuery创建的本地存储元素?

<ul id="names"> 
<li class="input-append"> 
<input type="text" name="hotel_name[]" id="hotel_name[]">  
<a class="add_name" href="#"><i>&#xf055;</i>add one more</a></li> 
    </ul> 

$('.add_name').click(function() { 
    $("#names").append('<li class="input-append">' 
     + '<input type="text" name="hotel_name[]" id="hotel_name[]">' 
      + ' <a class="remove_name add-on btn btn-danger" href="#"><i>&#xf056;</i>remove</a>' + '</li>'); 
     return false; }); 

有什么方法可以将创建的元素存储在LocalStorage中吗?

+3

您不能存储元素本身,但可以存储HTML字符串。你究竟做了什么!为什么您需要将元素存储在本地存储中? – adeneo 2013-04-07 19:13:22

+0

我很确定你不能。对不起 – sdespont 2013-04-07 19:13:25

回答

3

var foo = {1: [1, 2, 3]}; localStorage.setItem('foo', JSON.stringify(foo)); var fooFromLS = JSON.parse(localStorage.getItem('foo'));

1

尝试将元素存储为字符串。这里是一个网站,提供了一个很好的实现获取元素的outerHTML。 http://www.yelotofu.com/2008/08/jquery-outerhtml/

jQuery.fn.outerHTML = function(s) { 
    return (s) ? this.before(s).remove() 
    : jQuery("&lt;p&gt;").append(this.eq(0).clone()).html(); 
} 

存储该字符串,然后使用适当的jQuery方法重新插入元件。

+0

像这样工作'var foo = {1:[1,2,3]}; localStorage.setItem('foo',JSON.stringify(foo)); var fooFromLS = JSON.parse(localStorage.getItem('foo'));' – 2013-04-19 00:07:42

相关问题