我希望将文本输入的值记录到控制台,但是当我打开页面时,console.log() 为空。为什么是这样?
<input type="text" id="word"/>
//JavaScript
var newWord = document.getElementById("word").value;
console.log(newWord);
我希望将文本输入的值记录到控制台,但是当我打开页面时,console.log() 为空。为什么是这样?
<input type="text" id="word"/>
//JavaScript
var newWord = document.getElementById("word").value;
console.log(newWord);
确保添加事件处理程序。
将 onchange 事件侦听器添加到输入元素。
function func() {
var newWord = document.getElementById("word").value;
console.log(newWord);
}
<input type="text" id="word" onchange='func()'/>
您需要在输入中输入一个值或添加一个默认值
<input type="text" id="word" value="Hello"/>
var newWord = document.getElementById("word").value;
console.log(newWord);
这将记录值
用于.addEventListener在change触发事件时运行函数 - 这将在输入中的值更新并且焦点从输入框中移除时运行您的函数
document.getElementById('word').addEventListener('change', function () {
let newWord = this.value;
console.log(newWord);
});
<input type="text" id="word"/>
或者,您可以使用该input事件,该事件将在输入更改后立即触发
document.getElementById('word').addEventListener('input', function () {
let newWord = this.value;
console.log(newWord);
});
<input type="text" id="word"/>
我无法得到你的问题,但根据我的理解,当事件发生时,你需要使用一个函数来获取输入框的值。这是这样的代码。
<!DOCTYPE html>
<html>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" id="myinput" onkeypress="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById('myinput').value;
document.getElementById('demo').innerHTML = x;
}
</script>
</body>
</html>