我在文本区域附加一个按钮
i append a textarea with a button
$(".mydiv").append("<textarea id='myTextarea'></textarea><div class='sendReply btn btn-default'>my button</div>");然后,我将新文本写入textarea,并尝试通过单击功能从textarea获取新的写入值;
After that , i'm writing new texts into textarea and trying to get new writed value inside from textarea with this on click function ;
jQuery(document).on('click','.sendReply', function () { var myNewText = $("#myTextarea").val(); console.log(myNewText); });但是它说这是一个空字符串",如果我添加带有<textarea id="myTextarea">some text</textarea>这样的值的文本区域,我的功能会起作用并给我一些文本",但是如果我编辑textarea并单击sendReply按钮(我单击函数),它仍然给我一些文字",没有变化
But it says that this an "empty string" , if i add text area with a value like <textarea id="myTextarea">some text</textarea> my fucntion works and gives me "some text" but if i edit textarea and click sendReply button (my on click function), it is still gives me "some text" , it don't change
在添加文本区域后,如何获取已编辑的文本区域值?
How can i get edited textarea value after apppend a textarea?
推荐答案在附加HTML的同时,在.sendReply中有一个.
You have an . in .sendReply while appending the HTML
您只需要从.sendReply
使用
<div class='sendReply btn btn-default'>my button</div>"当您使用事件委托时,您的jQuery将正常工作.
As you are using Event delegation your jQuery will work.
您要多次添加具有相同ID的文本区域吗? $("#myTextarea").val()将始终显示ID为 myTextarea 的第一个文本区域的值.您可以使用通用类,然后使用 prev() 选择文本区域
As you are adding textarea with same ID multiple times? $("#myTextarea").val() will always show value of first textarea with id myTextarea. You can use a common class and then use prev() to select the textarea
查看示例
$(document).ready(function() { $(document).on('click', '.sendReply', function() { var myNewText = $(this).prev(".myTextarea").val(); alert(myNewText); }); for (var i = 0; i < 5; i++) { $(".mydiv").append("<textarea class='myTextarea'>some text</textarea><div class='sendReply btn btn-default'>my button</div>"); } });
<script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='mydiv'></div>
更多推荐
获取附加文本区域的值
发布评论