jQuery,如何克隆保存的元素?

时间:2013-04-22 12:52:52

标签: jquery

要演示,请参阅我的HTML:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
See it:
<pre>
print "Say hello"
</pre>
<p><b>==SEP==</b></p>
<pre>
class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded <a href="#voila1">tags</a>.
}
</pre>
</html>

在Chrome v26控制台中,我执行:

var pres_orig=$('pre').clone()
$('pre').replaceWith('<pre>spam</pre>')

然后我的问题:如何克隆保存的pres_orig中的<pre>内容,以便我的页面显示其原始内容?

我尝试过以下无法解决的问题:

$('pre').replaceWith(pres_orig)

enter image description here enter image description here

3 个答案:

答案 0 :(得分:1)

由于您有多个pre元素,没有识别值。您可以采取的一种方法是循环所有元素并将内部html存储在数组中。然后当你需要再次加载它们时,你可以循环它们并使用索引拉出数组html。

这样的事情:

//store all the data on load
var storage = [];
$("pre").each(function(){
   storage.push($(this).html()); 
});

//set the new html to "spam"
$("pre").html("spam");

//reload the original data
$("pre").each(function(index){
    $(this).html(storage[index]);
});

Here is a working example

答案 1 :(得分:0)

不要克隆。保存内部(或外部)HTML。将内部HTML插入pre。使用.html()获取内部HTML和.html(内容)来替换内部HTML。

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function() {
        var pres = [];
        // this is how you store it:
        $('pre').each(function(i) {
          pres[i] = $(this).html();
        });
        // this is how you restore it:
        $('pre').each(function(i) {
          $(this).html(pres[i] + "SPAM ;)");
        });
      });
    </script>
  </head>
  <body>
    See it:
    <pre>
      print "Say hello"
    </pre>
    <p><b>==SEP==</b></p>
    <pre>
      class Voila {
      public:
        // Voila
        static const string VOILA = "Voila";

        // will not interfere with embedded <a href="#voila1">tags</a>.
      }
    </pre>
  </body>
</html>

因此,如果要将此数组保存到文件或cookie,请使用JSON3对其进行序列化。

答案 2 :(得分:0)

我认为到目前为止我找到了最好的解决方案,只有一个声明:

for(var i=0; i<pres_orig.length; i++) 
    $('pre').eq(i).replaceWith(pres_orig.eq(i).clone());

OR

$('pre').each( function(i){ 
    $(this).replaceWith(pres_orig.eq(i).clone()) 
});

注意:使用clone()使pres_orig保持其独立副本,以便我们能够将其克隆回任何次。

enter image description here