首页 > 解决方案 > 如何动态更改 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>

标签: javascripthtmljquery

解决方案


$(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()


推荐阅读