簡體   English   中英

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

[英]How to clear textbox on HTML using Javascript

我有這樣的 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>

和這樣的外部 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="";
}

當我嘗試單擊頁面上的清除按鈕時,文本區域不清晰。 怎么了? 我該怎么辦?

只需將您的函數從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

如果你使用這樣的功能

function clearInput(element){
element.value="";
}

然后在輸入中添加這個

onfocus="clearInput(this)"

這可以多次用於任何文本字段或文本區域,因為對象的 id 是從它調用函數的地方傳遞的。

基拉

嘗試在定義 onclick 事件時在函數名稱之前添加 javascript: 。
像這樣的東西:

<input type="button" value="Clear" onclick='javascript: clear();'/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM