[英]Why does my function, that fills a textarea, only work the first time?
Javascript: 使用Javascript:
function editQuestion() {
$("body").on("click", ".edit_question", function(event) {
$(this).closest("form").find("textarea").text("sample text");
event.preventDefault();
});
}
$(document).ready(function() {
editQuestion();
});
HTML: HTML:
<form>
<textarea>ormar</textarea>
<div class="actions">
<a href="#" class="edit_question">Cancel</a>
</div>
</form>
When firing off the function by clicking the .edit_question
link, everything is working as expected the first time. 通过单击.edit_question
链接.edit_question
该功能时,所有功能.edit_question
预期首次运行。
But clicking more times (after manually removing the textarea content) doesn't do anything, why is this? 但是单击更多次(在手动删除textarea内容之后)没有任何作用,这是为什么?
.text()
only changes the initial value of the textarea, since the initial value is read from the element's content ( <textarea>Initial value</textarea>
). .text()
只改变textarea的初始值,由于初始值是从元素的内容读取( <textarea>Initial value</textarea>
)。
Once you modified the value, the current value is stored in the value
property of the DOM element. 修改值后,当前值将存储在DOM元素的value
属性中。 Changing the initial value after the textarea was modified doesn't have any effect. 修改文本区域后更改初始值没有任何效果。
That's why you should use .val()
intead of .text()
. 这就是为什么您应该在.text()
.val()
使用。
Updated Demo compare with Original Demo 更新的演示与原始演示比较
Use .val()
instead of .text()
in case of inputs. 输入时,请使用.val()
而不是.text()
。
Check this, 检查一下
$(document).ready(function () {
$(document).on("click", ".edit_question", function (event) {
$(this).closest("form").find("textarea").val('sample text');
event.preventDefault();
});
});
Note: The .text() method cannot be used on form inputs or scripts. 注意: .text()方法不能在表单输入或脚本上使用。
Try using the .val() method rather than .text() method for textarea 尝试将.val()方法而不是.text()方法用于textarea
From documentation page: The .text() method cannot be used on form inputs or scripts. 从文档页面: .text()方法不能在表单输入或脚本上使用。 To set or get the text value of input or textarea elements, use the .val() method. 若要设置或获取输入或textarea元素的文本值,请使用.val()方法。 To get the value of a script element, use the .html() method. 若要获取脚本元素的值,请使用.html()方法。
link: http://api.jquery.com/text/ 链接: http : //api.jquery.com/text/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.