How to store in browser Local Storage elements created by jQuery?

浪尽此生 提交于 2019-12-25 02:56:34

问题


I'm using jQuery to add/remove input fields.

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

Is there any way to store created elements in LocalStorage?


回答1:


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




回答2:


Try storing the element as a string. Here is a site that gives a nice implementation getting the outerHTML of an element. 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();
}

Store that string and then reinsert the element using the appropriate jQuery method.



来源:https://stackoverflow.com/questions/15866583/how-to-store-in-browser-local-storage-elements-created-by-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!