How to store in browser Local Storage elements cre

2019-09-06 00:17发布

问题:

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.