如何在 HTML 中建立一個新增文字的按鈕?
假設我們的 HTML 按鈕是以下內容 −
<button id="clickButton">Click the button to add the input into the belowText Box</button>
使用 document.getElementById() 在點選按鈕時向 <input> 中新增文字。以下為程式碼 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <button id="clickButton">Click the button to add the input into the below Text Box</button> <br/><br /> <input id="readTheInput" /> <script> document.getElementById("clickButton").addEventListener("click", () =>{ document.getElementById("readTheInput").value += "JavaScript"; }); </script> </body> </html>
要執行上述程式,儲存檔名“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“Open with Live Server”選項。
輸出
這將產生以下輸出 −
在此,我將點選按鈕兩次。這將產生以下輸出 −
廣告