在更新<textarea>
标签内的值时遇到问题。过程是这样的,在textarea中有一个初始值,然后用户对其进行更改。如果我想使用js脚本(通过按钮实现)来进一步修改值,那么它根本不起作用。但是,如果我们对文本区域不执行任何操作,则该按钮将正常工作。对我来说很奇怪。谁能对此有所启示?代码在下面发布。
$(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>
答案 0 :(得分:1)
$(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() 。