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

jQuery,如何克隆回保存的元素?,jquery,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

要演示,请参见我的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>
不要克隆。保存内部(或外部)HTML。将内部HTML插入到pre。使用.html()获取内部html,使用.html(内容)替换内部html


$(函数(){
var-pres=[];
//这是您存储它的方式:
$('pre')。每个(函数(i){
pres[i]=$(this.html();
});
//以下是恢复它的方式:
$('pre')。每个(函数(i){
$(this.html(pres[i]+“SPAM;”);
});
});
请看:
打印“打招呼”
==九月==

瞧{ 公众: //瞧 静态常量字符串VOILA=“VOILA”; //不会干扰嵌入式系统。 }

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

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

大概是这样的:


我想我找到了迄今为止最好的解决方案,只有一句话:

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


为什么不直接存储内部HTML然后更改它,而不是更改实际的
pre
元素呢。如下所示:
var orig=$(“pre”).html()$(“pre”).html(“垃圾邮件”)$(“pre”).html(orig)未按预期工作。你自己试过吗?在哪个浏览器中,哪个版本?它可以正常工作,但不能正常工作。请用两个s试试。使用你的代码,它们都会被替换为相同的内容。是的,或者当然会。我想如果你需要更具体的话,你会知道如何使用选择器。我建议您使用
id
作为您需要参考的确切id。这样做的好处是什么?您可以获得可序列化的数据,它很简单,很容易修改文本内容。谢谢。这个符合我的期望+1从我这里。如果将
replaceWith
替换为类似
copyFrom
的内容,我会更好,这样我就可以省略
clone
var pres_orig=$('pre').clone()
$('pre').replaceWith('<pre>spam</pre>')
$('pre').replaceWith(pres_orig)
<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>
//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]);
});
for(var i=0; i<pres_orig.length; i++) 
    $('pre').eq(i).replaceWith(pres_orig.eq(i).clone());
$('pre').each( function(i){ 
    $(this).replaceWith(pres_orig.eq(i).clone()) 
});