使用jquery复制文本并粘贴到textarea中

时间:2015-11-01 18:21:41

标签: javascript jquery textarea

在论坛中,我想复制原始帖子并引用它并使用jQuery粘贴到文本区域:

enter image description here

我发现了this帖子。但是,它并不适用我真正需要的东西。

2 个答案:

答案 0 :(得分:1)

如果原始文本位于<div>元素中,请执行以下操作:

<div id="original">
    Original text...
</div>

和按钮如下:

<button id="copy">Copy Text</button>

<textarea>一样:

<textarea id="paste"></textarea>

您可以简单地使用jQuery获取原始值并将其粘贴到<textarea>中,如下所示:

$("#copy").click(function() {
    $("#paste").val($("original").text());
});

请参阅this example

答案 1 :(得分:1)

因此,假设您在ID为original的div中包含“原始文本”,复制按钮的ID为copy,而textarea的ID为paste-here。那么这个简单的片段应该是它:

//When the user clicks the copy button...
$('#copy').click(function() {
    //Take the text of the div...
    var text = $('#original').text();
    //...and put it in the div:
    $('#paste-here').val(text);
});

这将用原始文本替换文本区域的内容。如果您只想将其添加到最后,请改为:

    //Take the text of the textarea, a linebreak, and the text of the div...
    var text = $('#paste-here').val() + '\n' + $('#original').text();
    //...and put it in the div:
    $('#paste-here').val(text);