解码克隆的div的HTML内容

时间:2019-02-28 16:31:48

标签: javascript jquery html clone decode

我正在尝试寻找一种方法来解码使用jQuery克隆的div的HTML代码。
原始div是由AngularJS变量动态生成的,我想在<pre>元素中显示其克隆版本,以便显示由于用户输入而获得的DOM。

$(document).ready(function() {
  $('#cloneIt').on('click', function() {
    $('#clone').children().clone().appendTo("pre");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="clone" class="hidden">
  <table>
    <tbody>
      <tr ng-repeat="language in languages">
        <td class="ico"><img src="assets/images/ico/audio.png"></td>
        <td class="r-text"><a href="assets/audio/{{ language.audio }}.mp3" target="_blank">Ascolta la sintesi in <strong>{{ language.name }}</strong></a></td>
        <td class="ico"><img src="assets/images/ico/pdf.png"></td>
        <td class="r-text"><a href="assets/pdf/{{ language.pdf }}.pdf" target="_blank">Leggi la sintesi in <strong>{{ language.name }}</strong></a></td>
      </tr>
    </tbody>
  </table>
</div>
<pre class="prettyprint"></pre>

<p>
  <button id="cloneIt" class="btn btn-warning">Generate source code</button>
</p>

通过按下按钮,我想要的输出(在AngularJS完成工作之后)应该是:

&lt;table&gt;   
 &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td class=&quot;ico&quot;&gt;&lt;img src=&quot;assets/images/ico/audio.png&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;r-text&quot;&gt;&lt;a href=&quot;assets/audio/Audio-link_01.mp3&quot; target=&quot;_blank&quot;&gt;Listen to &lt;strong&gt;Italian&lt;/strong&gt; track&lt;/a&gt;&lt;/td&gt;
      &lt;td class=&quot;ico&quot;&gt;&lt;img src=&quot;assets/images/ico/pdf.png&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;r-text&quot;&gt;&lt;a href=&quot;assets/pdf/Pdf-link_01.pdf&quot; target=&quot;_blank&quot;&gt;Read &lt;strong&gt;Italian&lt;/strong&gt; transcript&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    [and so on...]
  &lt;/tbody&gt;
&lt;/table&gt;  

如何解码克隆的div的HTML内容?

如果您能在这种情况下为我提供帮助,我感到很高兴。谢谢大家。

1 个答案:

答案 0 :(得分:2)

要实现所需的功能,请将html()元素的#clone设置为text()元素的pre,如下所示:

$(document).ready(function() {
  $('#cloneIt').on('click', function() {
    $("pre").text($('#clone').html());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="clone" class="hidden">
  <table>
    <tbody>
      <tr ng-repeat="language in languages">
        <td class="ico"><img src="assets/images/ico/audio.png"></td>
        <td class="r-text"><a href="assets/audio/{{ language.audio }}.mp3" target="_blank">Ascolta la sintesi in <strong>{{ language.name }}</strong></a></td>
        <td class="ico"><img src="assets/images/ico/pdf.png"></td>
        <td class="r-text"><a href="assets/pdf/{{ language.pdf }}.pdf" target="_blank">Leggi la sintesi in <strong>{{ language.name }}</strong></a></td>
      </tr>
    </tbody>
  </table>
</div>
<pre class="prettyprint"></pre>

<p>
  <button id="cloneIt" class="btn btn-warning">Generate source code</button>
</p>