简体   繁体   English

如何获取 JavaScript 中文本类型输入中的值?

[英]How to get the value inside the input of type text in JavaScript?

 var data = document.getElementById('myFieldId'); console.log(data.value);
 <.DOCTYPE html> <html> <head> </head> <body> <input type="text" id="myFieldId"/> <script src="main.js"></script> </body> </html>

I expect when I write any text in the input, it would print the corresponding text.我希望当我在输入中写任何文本时,它会打印相应的文本。 But I don't get anything in the console.但我在控制台中没有得到任何东西。 What should I do?我应该怎么办?

You need to add an event listener that executes as soon as someone inputs text.您需要添加一个在有人输入文本时立即执行的事件侦听器。

There is no such thing as binding a variable to a text input ;没有将变量绑定到文本输入这样的事情; this needs to be implemented by yourself.这需要自己实现。

See this example:看这个例子:

 const data = document.getElementById('myFieldId'); data.addEventListener( 'input', // first argument is the name of the event you want to react to // second argument is the function that should execute when the event occurs function(inputEvent) { console.log(data.value); } );
 <input type="text" id="myFieldId"/>

You code start at load page so is empty, i add an onchange event so when you finish to write console.log will output the value.您的代码从加载页面开始,所以是空的,我添加了一个onchange事件,所以当您完成编写console.log时将 output 值。

 var data = document.getElementById('myFieldId'); data.onchange = function() { console.log(this.value); };
 <.DOCTYPE html> <html> <head> </head> <body> <input type="text" id="myFieldId"/> <script src="main.js"></script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM