如何使用jQuery清除文本区域 [英] How do I clear a textarea with jquery

查看:129
本文介绍了如何使用jQuery清除文本区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经回答了,但是这里有一个完整的例子供以后参考.

This question has been answered, but for future reference here is a full example.

您可以根据需要多次单击添加"按钮和清除"按钮,它将起作用.但是,一旦在文本框中键入内容,则清除和添加按钮将不起作用.

You can click the add button and clear button as many times as you want and it will work. But once you type something in the text box, then the clear and and add buttons do not work.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $("#add").click(function(){

        $("#box").append("Test, ")
    });

    $("#clean").click(function(){
        $("#box").text("")
    });

});
</script>
</head>
<body>

<button id="add">ADD</button><br/>
<textarea rows="10" cols="50" id="box"></textarea><br/>
<button id="clean">Clear Box</button>

</body>
</html>

推荐答案

在处理需要用户输入的元素时,应使用jQuery的val函数:

When dealing with elements that expect input from the user you should use jQuery's val function:

$(function() {
  $('#b1').click(function() {
      $("#textarea").val($("#textarea").val() + "This is a test");
  });
  $('#c1').click(function() {
    $("#textarea").val("")
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea><br />
<button id="b1">Append</button> <button id="c1">Clear</button> 

append函数更改了DOM,这不是您要在此处执行的操作(这是破坏textarea元素默认行为的原因).

The append function changes the DOM, and this is not what you are trying to do here (This is what breaks the default behavior of the textarea element).

这篇关于如何使用jQuery清除文本区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆