使用 JavaScript 向 HTML 元素添加 oninput 属性?
javascriptweb developmentobject oriented programminghtml更新于 2025/8/19 3:56:17
为此,请使用 document.getElementById() 概念以及 addEventListener()。 以下是 JavaScript 代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=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>
<label> Enter the value:</label>
<input id="enterValue" type="text">
</body>
<script>
document.getElementById('enterValue').addEventListener("input", function () {
console.log('you have entered the value');
});
</script>
</html>
要运行上述程序,请保存文件名anyName.html(index.html),然后右键单击该文件,在 VS 代码编辑器中选择使用实时服务器打开选项。
输出

当用户输入一个值时 −

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

