如何使用Javascript清除HTML上的文本框

Ady*_*ari 2 html javascript textarea button clear

我有像这样的HTML代码

<html>
<script type="text/javascript" src='LatihanKuisJs.js'></script>
    <body>
        <form name="kuis">
            <table border="1" width="50%">
                <tr>
                    <th colspan="2" >Celcius
                </tr>
                <tr>
                        <td align="center" width="80%">Kelvin</td>
                        <td align="center"><input type="text" id="kelvin">
                        </td>
                </tr>
                <tr>
                    <td align="center" width="80%">Reamur</td>
                    <td align="center"><input type="text" id="reamur"></td>
                </tr>
                <tr>
                    <td align="center" width="80%">Fahrenheit</td>
                    <td align="center"><input type="text" id="fahrenheit"></td>
                </tr>
            </table>
            <input type="button" value="Calculate" onclick='calculateCelcius();'/>
            <br/><br/>
            <textarea rows="20" cols="90" id="textarea">
            </textarea>
            <br/><br/>
            <input type="button" value="Clear" onclick='clear();'/>
        </form>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

和外部JavaScript函数如下:

function calculateCelcius(){
    var kelvin = document.getElementById('kelvin');
    var reamur = document.getElementById('reamur');
    var fahrenheit = document.getElementById('fahrenheit');
    var textarea = document.getElementById('textarea');

    var hasil=(kelvin.value*1 + reamur.value*1 + fahrenheit.value*1);
    textarea.value += hasil + '\n';
}

function clear(){
    document.getElementById("textarea").value="";
}
Run Code Online (Sandbox Code Playgroud)

当我尝试单击页面上的清除按钮时,文本区域不清晰.怎么了?我该怎么办?

Vis*_*ioN 10

只需将您的功能重命名clear为类似的功能即可clearTextarea.

clear()方法指的是过时的document.clear()方法,在MDN中描述为:

此方法用于清除Mozilla早期(1.0之前版本)中的整个指定文档.在最新版本的基于Mozilla的应用程序以及Internet Explorer和Netscape 4中,此方法不执行任何操作.

另外根据HTML5规范:

clear()方法必须无所作为.

参考文献:

  1. https://developer.mozilla.org/en-US/docs/DOM/document.clear
  2. http://www.whatwg.org/specs/web-apps/current-work/multipage/obsolete.html#dom-document-clear