我可以将jQuery DOM克隆存储在本地存储中以供以后使用吗?

时间:2021-11-07 19:41:32

I would like to store a jQuery object representing a DOM element, for later use. Already I have these methods that carry out storage and retrieval of objects and text, to and from localStorage:

我想存储一个表示DOM元素的jQuery对象,供以后使用。我已经有这些方法可以在localStorage中存储和检索对象和文本:

 var Data = {
  set: function(key, value, session) {
    if (!key) {return;}

    if (typeof value === "object") {
      value = JSON.stringify(value);
    }
    if(session){
        sessionStorage.setItem(key, value);
    }else{
        localStorage.setItem(key, value);
    }
  },
  get: function(key, session) {
    if(session){
        var value = sessionStorage.getItem(key);
    }else{
        var value = localStorage.getItem(key);
    }

    if (!value) {return;}

    // assume it is an object that has been stringified
    if (value[0] === "{" || value[0] === "[") {
      value = JSON.parse(value);
    }

    return value;
  }
}

It is based, thankfully, on a Stack Overflow source, and works well for simple objects, apart from strings.

幸运的是,它基于Stack Overflow源,除了字符串之外,它还适用于简单对象。

What I'm thinking about is to do this:

我在想的是这样做:

$clone = $('#myform').clone(true);
Data.set('clonedata', $clone);

And then, much later, elsewhere:

然后,很久以后,其他地方:

$retrieved = Data.get('clonedata');

Problem is, it doesn't seem to be working in this case. Is there a fundamental reason why a jQuery object cannot be serialized and deserialized in this manner?

问题是,在这种情况下它似乎不起作用。是否有一个基本原因导致jQuery对象无法以这种方式序列化和反序列化?

How can this can be useful? One case is for persisting (autosaving) form data in localStorage as the user fills a long form. Then the information can be offered back after, say a network outage or inadvertent browser navigation or closure.

这怎么可能有用?一种情况是在用户填写长格式时在localStorage中持久化(自动保存)表单数据。然后,可以在网络中断或无意的浏览器导航或关闭之后提供信息。

1 个解决方案

#1


1  

you can use garlic.js for local persisting. hopefully this link may help you out.simple use, just include the js file and add data-persist="garlic" as a form attribute.it can save your form data even if your machine power failure.you can download the js file from here.

你可以使用garlic.js进行本地持久化。希望这个链接可以帮助你简单使用,只需包含js文件并添加data-persist =“garlic”作为表单属性。即使您的机器电源故障,也可以保存表单数据。您可以从中下载js文件这里。

http://garlicjs.org/

http://garlicjs.org/

#1


1  

you can use garlic.js for local persisting. hopefully this link may help you out.simple use, just include the js file and add data-persist="garlic" as a form attribute.it can save your form data even if your machine power failure.you can download the js file from here.

你可以使用garlic.js进行本地持久化。希望这个链接可以帮助你简单使用,只需包含js文件并添加data-persist =“garlic”作为表单属性。即使您的机器电源故障,也可以保存表单数据。您可以从中下载js文件这里。

http://garlicjs.org/

http://garlicjs.org/