使用jQuery克隆文本

时间:2016-01-08 08:30:57

标签: jquery wordpress

我想将文字从我网站的一部分复制到另一部分。您如何修改此代码以匹配我的HTML?

jQuery:

$('caption span').each(function(index) {
    $(this).text($(this).closest('table').find('th').text());
});

HTML:

<span class="original">Clone This Text #1</span>
<span class="copy">Place New Text Here</span>

enter image description here

1 个答案:

答案 0 :(得分:0)

使用jQuery的.text()函数从<span class="original">获取文本节点,并将<span class="copy">的文本节点设置为先前的值。阅读文档here

使用以下jQuery代码:

&#13;
&#13;
$('.copy').text($('.original').text());

$('button').click(function () {
  $('.copy-2').text($('.original-2').text());
});
&#13;
.copy {
  color: gray;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h3>Cloning of text is ran here on load</h3>
<span class="original">Clone This Text #1</span> <br>
<span class="copy">Place New Text Here</span>

<h3>Here, you can see it happen on button click</h3>
<span class="original-2">Clone This Text #2</span> <br>
<span class="copy-2">Place New Text Here</span>
<button>click</button>
&#13;
&#13;
&#13;