如何制作一个按钮,在 HTML <input> 中添加文本?
javascriptweb developmentobject oriented programming更新于 2025/11/12 20:28:17
假设以下是我们的 HTML 按钮 −
<button id="clickButton">单击按钮将输入添加到下面的文本框</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 编辑器中选择选项"使用 Live Server 打开"。
输出
将产生以下输出 −

在这里,我将单击按钮两次。这将产生以下输出−

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

