如何在手动更新 TEXTAREA 值后强制 jQuery.text() 工作?

How to force jQuery.text() working even after manual updating the TEXTAREA value?

我刚刚注意到 jQuery text(...) method only sets the content of a TEXTAREA, if if has not been updated manually. For example (also on jsFiddle):

$('#myButton').click(function() {
   $('#myText').text(Date.now); 
});
<textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script>

现在,当我单击 Go! 时,TEXTAREA 的内容将更新为当前时间戳。我也可以做多次。在职的。但是如果我手动更改文本(例如通过删除或添加字符),它就会停止工作。

我也尝试了val(...)方法。它按预期工作,无论文本字段上的手动更改如何。

如何在手动更改后让 jQuery.text(...) 工作?

您的问题似乎表明您知道可以使用 val 但选择不使用。所以我尝试了各种选项,但我认为您不能可靠地使用 text 来设置文本区域。

因此,由于设置 textarea 值的正确方法是使用 val,因此请使用 val。 :-) 如果您这样做,无论 textarea 是否由用户编辑,它都会起作用:

$('#myButton').click(function() {
   $('#myText').val(Date.now); 
});
<textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script>