使用jQuery将标记中的文本插入textarea

问题描述 投票:0回答:2

我一直在阅读几页,以便弄清楚如何将html标签中的内容插入到textarea元素中。

我在stackoverflow上找到了一个an example的页面,我试图修改它,但是因为我没有使用jquery的经验,我(当然)很快就遇到了麻烦!因为我根本不知道如何将html标签上的click事件与一个插入html标签内容的事件“连接”,例如:

<p>something</p>

成为textarea元素。

这是我到目前为止:

$("p").click(function() {
 $(this).
  $("textarea").insertAtCaret('text');

主要问题是写后:

$(this).????

我做了一个jsfiddle我的项目显示

我希望有人能帮助我,或者至少指出我正确的方向 - 谢谢你提前:o)

jquery html
2个回答
0
投票

获取标签内容使用text()并获取输入/ textarea内容使用val()也编辑其内容使用文本('some content')/ val('some content')

$("p").click(function() {
var content=$(this).text();
$("textarea").val(content);

0
投票

我为你制作了一个jsfiddle,它从2 div获得名字和姓氏(你可以将它们改为p,无论如何),当你点击按钮时,textarea的文本将替换为新的名字。希望它有效,请确认它是否解决了您的问题。

HTML:

    <h2>
we have 2 paragraph and we want to add them ro our textare.
</h2>

<div class="FName">Arya</div>
<div class="LName">Ag</div>
<form action="#">
  <textarea name="message" rows="10" cols="30">
Insert [firstname] or [lastname] at the position of the cursor in this textarea while keeping the content already there 
</textarea>
<br/>
<br/>
<input type="button" value="update" id="updater"/>

JS:

$('#updater').on('click',function(){
var FName= $('.FName').text();
var LName= $('.LName').text();

$('textarea').text($('textarea').val().replace("[firstname]",FName).replace('[lastname]',LName));

})
© www.soinside.com 2019 - 2024. All rights reserved.