【问题标题】:How to store in browser Local Storage elements created by jQuery?如何在浏览器中存储由 jQuery 创建的本地存储元素?
【发布时间】:2013-04-07 19:07:01
【问题描述】:

我正在使用 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 中?

【问题讨论】:

  • 您不能存储元素本身,但可以存储 HTML 字符串。你到底想做什么!为什么需要将元素存储在本地存储中?
  • 我很确定你不能。对不起

标签: jquery html local-storage


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试将元素存储为字符串。这是一个站点,它提供了一个很好的实现来获取元素的外层HTML。 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 方法重新插入该元素。

    【讨论】:

    • 像这样工作var foo = {1: [1, 2, 3]}; localStorage.setItem('foo', JSON.stringify(foo)); var fooFromLS = JSON.parse(localStorage.getItem('foo'));
    猜你喜欢
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多