使用 JavaScript 向 HTML 元素添加 oninput 属性?

javascriptweb developmentobject oriented programminghtml

为此,请使用 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 代码编辑器中选择使用实时服务器打开选项。

输出

当用户输入一个值时 −


相关文章