首页 > 解决方案 > 如何使用 jquery 将 html 代码解析为可复制的文本

问题描述

我得到了这个东西来把琴弦放在一起。我发现以某种方式存储 URL 部分的最简单方法是在 div 中。无论如何,我想要的是将所有这些结合在一起并输出为用户可以复制和使用的代码。但是,即使放在一个<code>or<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>

标签: jquery

解决方案


1)您要求 idoutput_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>

这回答了你的问题吗?请随时询问有关我的代码的任何问题:)


推荐阅读