javascript - 如何动态更改 textarea 值?
问题描述
我在更新<textarea>
标签中的值时遇到问题。过程是这样的,textarea里面有一个初始值,然后用户改变它。如果我想使用 js 脚本(通过按钮实现)进一步修改该值,它根本不起作用。但是,如果我们在 textarea 上什么都不做,按钮就可以正常工作。对我来说太奇怪了。任何人都可以对此有所了解吗?代码贴在下面。
$(document).ready(function() {
$("#mybutton").click(function() {
var mystring = "The previous textarea value is <br><em>" + $("#myarea").val() + "</em>";
$("#myarea").html("Star wars"); // this line doesn't work after editting the textarea but works if you do not edit anything, why?
$("#placeholder").html(mystring);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div>Input whatever you want</div>
<textarea id="myarea" style="width: 300px; height: 70px">Initial text</textarea>
<div>
<button id="mybutton">Click after editing</button>
<br> The button is supposed to change the text to <em>Star wars</em>.
</div>
<div id="placeholder"></div>
</body>
解决方案
$(document).ready(function() {
$("#mybutton").click(function() {
var mystring = "The previous textarea value is <br><em>" + $("#myarea").val() + "</em>";
$("#myarea").val("Star wars"); //The changes have to be made on this line
$("#placeholder").html(mystring);
});
});
为了更改 textarea 的值,请使用 val() 而不是 html()。
推荐阅读
- php - 我在 Laravel 5.6 中存储大型数组时遇到问题
- android - 如何制作始终在 Native Android 中水平捕获的自定义相机?
- c++ - UINT GetDriveTypeA(LPCSTR)':无法将参数 1 从 'LPCWSTR' 转换为 'LPCSTR'?
- c# - 与正确配置的同步相比,异步模型真的会在吞吐量方面带来好处吗?
- java - [AWS][Azure][Multi-Cloud] Regarding multi cloud resource access using sdk's
- macos - macOS 应用程序对所有按钮事件都没有响应
- r - Passing reactive data to global environment
- css - Bootstrap 4 Right justifiy Button group inside list group
- python-3.x - 尽管安装了更新版本,Python interpeter 仍使用以前版本的 numpy - 如何修复?
- php - 从 PHP 面板控制 Python 脚本