我一直在 jquery 中寻找一个函数,它可以让我“复制并粘贴”某个元素内的文本,即
<li>
或 <div>
内并将其放入另一个元素中。这应该在不破坏从中复制文本的元素的情况下完成。
我有一个 jsfiddle 文档,展示了我的最佳尝试和更实用的描述:http://jsfiddle.net/HDBLd/
非常感谢
P.S 我想澄清一下,我不想将元素内的文本复制到用户剪贴板,只是复制到另一个元素。
要将 HTML 从一个元素发送到另一个元素,您可以简单地使用原始元素的
html()
输出作为目标的源,如下所示:
jQuery($ => {
$('li').on('click', function() {
$('#lorem').html($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<div id="lorem">
This is the text that should change
</div>
<div id="impsum">
<ul>
<li>This is the text that will replace the other piece of text. I need to find a function that will just copy the text in here - not the whole li with the bullet as well.</li>
</ul>
</div>
请注意,如果您想忽略原始元素中的任何 HTML,也可以使用
text()
代替 html()
。
$("#lorem").html($(this).html());
你几乎做对了,看看text()
$("#lorem").text($(this).text());