Javascript 为什么我能';是否将DOM元素定义为全局变量?

Javascript 为什么我能';是否将DOM元素定义为全局变量?,javascript,dom,Javascript,Dom,我正在处理一个表单,希望使用Javascript输出表单输入 所以我有以下脚本: <script> function showName() { var box = document.getElementById("lorem").value; console.log(box); } showName(); </script> ` 请问,我做错了什么?你可以用同样的。这不是问题。如果仍然出现空错误,我建议将脚本添加到文档末尾,或将其包含在document.

我正在处理一个表单,希望使用Javascript输出表单输入

所以我有以下脚本:

<script>
function showName() {
  var box = document.getElementById("lorem").value;

  console.log(box); 
}

showName(); 
</script> `

请问,我做错了什么?

你可以用同样的。这不是问题。如果仍然出现空错误,我建议将脚本添加到文档末尾,或将其包含在
document.addEventListener(“DOMContentLoaded”,function(event){
块中,如下所示

document.addEventListener(“DOMContentLoaded”),函数(事件){
变量框=document.getElementById(“lorem”).value;
函数showName(){
控制台日志(框);
}
showName();
});

声明时,
的值是
lorem
元素的初始值。您可能需要的是:

var box = document.getElementById('lorem');

function showName() {
    console.log(box.value); // <-- get the current value
}

// Outputs the current value, initially it will be empty
// of course, until you change your input and call the 
// function again
showName(); 
var-box=document.getElementById('lorem');
函数showName(){

console.log(box.value);//您可以在关闭
标记之前将脚本放在末尾,或者按照@jafarbtech的建议添加一个事件侦听器以等待加载DOM内容。

在开发控制台中是否有任何错误?如果没有,则
input 35; lorem
是否有任何初始值?如何添加事件侦听器?我已经计算过了退出。谢谢。没问题。请退出获取有关如何等待DOM加载的更多信息。问题是我想让函数触发器“onclick”
var box = document.getElementById('lorem');

function showName() {
    console.log(box.value); // <-- get the current value
}

// Outputs the current value, initially it will be empty
// of course, until you change your input and call the 
// function again
showName();