2

実演するには、私の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>')

それから私の質問:<pre>私のページが元のコンテンツを表示するように、保存された pres_orig からコンテンツを複製する方法は?

私は動作しない次のことを試しました:

$('pre').replaceWith(pres_orig)

ここに画像の説明を入力 ここに画像の説明を入力

4

3 に答える 3

1

pre識別値のない複数の要素があるため。1 つの方法は、すべての要素をループして、内部の 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]);
});

これが実際の例です

于 2013-04-22T14:00:18.670 に答える
0

クローンしないでください。内部 (または外部) HTML を保存します。内部 HTML を pre に挿入します。.html() を使用して内部 HTML を取得し、.html(content) を使用して内部 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を使用してシリアル化します。

于 2013-04-22T13:03:42.337 に答える