如何使用jQuery将HTML代码解析为可复制文本

时间:2019-03-14 08:54:35

标签: jquery

我已经把这东西放在一起了。我发现以某种方式在div中存储URL部分的最简单方法。无论如何,我想要的是将所有这些组合在一起并输出为用户可以复制和使用的代码。但是,即使将HTML放在<code><pre>元素中,HTML也会继续渲染。 IDK我在做什么错。

$(document).ready(function() {
  $("#generate").click(function() {
    $("#output_code").show;
    var stuff0 = '<code>';
    var stuff1 = $('#stuff1').text();
    var stuff2 = $('#username').val();
    var stuff3 = $('#stuff3').text();
    var stuff4 = $('#invite_text').val();
    var stuff5 = $('#stuff5').text();
    var stuff6 = '</code>';

    $('#output_code').append(stuff0 + stuff1 + stuff2 + stuff3 + stuff4 + stuff5 + stuff6);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Username: <input type="text" id="username"><br/>
Invitation text: <input type="text" id="invite_text" value="Follow me on the site!">
<a id="generate">generate link</a>
<div id="stuff1" style="display: none;">
  SOME HTML
</div>
<div id="stuff3" style="display: none;">
  SOME HTML
</div>
<div id="stuff5" style="display: none;">
  SOME HTML
</div>

1 个答案:

答案 0 :(得分:0)

1)您要让ID output_code显示在您的JQuery中,但从未在您的HTML代码中定义它!

2)用正则表达式替换其HTML代码<>的所有HTML标签(&#60;&#62;

3)对于剪贴板中的副本,我用代码创建了一个临时输入,然后选择它并复制了内容。最后,如您所见,我删除了临时输入

$(document).ready(function() {

  $("#generate").click(function() {
    $("#output_code").show;
    var stuff1 = $('#stuff1').html();
    var stuff2 = $('#username').val();
    var stuff3 = $('#stuff3').html();
    var stuff4 = $('#invite_text').val();
    var stuff5 = $('#stuff5').html();
    
    var all_code = stuff1 + stuff2 + stuff3 + stuff4 + stuff5;
    
    var all_code_formatted = all_code
    .split('<')
    .join('&#60;')
    .split('>')
    .join('&#62;'); // replace HTML tags, I'm pretty sure there's a better way to do it with regex but I don't know how to do it
    
    $('#output_code').html('<pre>' + all_code_formatted + '</pre>'); // Render the formatted code
    
    $('#output').html(all_code); // Render the result
    
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(all_code).select();
    document.execCommand("copy");
    $temp.remove(); // Create temporary <input> with your code non formatted, select and copy it and then remove the <input>
    
  });
  
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Username: <input type="text" id="username"><br/>
Invitation text: <input type="text" id="invite_text" value="Follow me on the site!">
<a id="generate">generate link</a>
<div id="stuff1" style="display: none;">
  <a href="https://www.example.com">SOME HTML</a>
</div>
<div id="stuff3" style="display: none;">
  <div>SOME HTML</div>
</div>
<div id="stuff5" style="display: none;">
  <p>SOME HTML</p>
</div>

<h2>The code</h2>
<div id="output_code"></div>

<h2>What it renders</h2>
<div id="output"></div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="10" cols="50"></textarea>

您的问题得到这个答案了吗?请随时问关于我的代码的任何问题:)