gpt4 book ai didi

JavaScript 将 HTML 复制到剪贴板将 < > 解释为 < 和 >

转载 作者:行者123 更新时间:2023-11-28 07:03:06 25 4
gpt4 key购买 nike

我可以让 JavaScript 将 DIV 的内容复制到剪贴板,但 HTML 标记 < & > 以 < 和 > 形式出现,而不是小于号或大于号。任何想法如何解决?链接到似乎不起作用但在本地有效的 fiddle 。 FIDDLE

JS

function copyToClipboard(elementId) {

// Create a "hidden" input
var aux = document.createElement("input");

// Assign it the value of the specified element
aux.setAttribute("value", document.getElementById(elementId).innerHTML);

// Append it to the body
document.body.appendChild(aux);

// Highlight its content
aux.select();

// Copy the highlighted text
document.execCommand("copy");

// Remove it from the body
document.body.removeChild(aux);

}

HTML

        <div style="display:none" >
<p id="p1">Content 3 blocks</p></div>

<button onclick="copyToClipboard('p1')">Copy 1 section</button><br/>
<button onclick="copyToClipboard('p2')">Copy 2 section</button><br/>



<textarea name="textarea" id="p2" cols="45" rows="5"><div class="content-section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h4 class="pumpkin-txt">Content Section - 4</h4>
</div>
<p>Some text here</p>
<br>
<h5>More text here</h5>
</div>
</div>
</div>
</div></textarea>

最佳答案

发生这种情况是因为 innerHTML 正在返回有效的 HTML 内容。 “<”不是节点值中的有效内部内容,因为它是 HTML 代码。您需要像这样自己更换它们:

//Just an example, you need to replace all possible offending characters
aux.setAttribute(
"value",
document.getElementById(elementId).innerHTML.replace( /&lt;/g, "<" )
.replace( /&gt;/g, ">" )
.replace( /&quot;/g, "\"" )
);

Working JSFiddle

关于JavaScript 将 HTML 复制到剪贴板将 < > 解释为 < 和 >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com