为什么我不能将DOM元素定义为全局变量?

时间:2017-06-09 05:32:17

标签: javascript dom

我正在处理表单并希望使用Javascript输出表单输入。

所以我有以下脚本:

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

  console.log(box); 
}

showName(); 
</script> `

上面的代码工作得很好,但我希望var box = document.getElementById("lorem").value;是一个全局变量,这样我就可以在其他函数中使用它而无需重新声明它。

所以当我有这个时它不输出任何东西: `

<script>
//Declared outside the function
var box = document.getElementById("lorem").value;

function showName() {
  console.log(box); 
}

showName(); 
</script>

拜托,我做错了什么?

3 个答案:

答案 0 :(得分:0)

您可以使用相同的。这不成问题。如果您仍然收到空错误,我建议您在文档末尾添加脚本,或将其封装在document.addEventListener("DOMContentLoaded", function(event) {块中,如下所示

document.addEventListener("DOMContentLoaded", function(event) {
var box = document.getElementById("lorem").value;
function showName() {


console.log(box); 

     }
showName(); 
});
<input type="text" value="hai" id="lorem"/>

答案 1 :(得分:0)

box的值是您声明它时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(); 

编辑:需要加载DOM才能使其生效,因此请务必将脚本标记放在<body>

的最后

答案 2 :(得分:0)

您可以在关闭<body>标记之前将脚本一直放在最后,或者像@jafarbtech建议那样执行,并添加一个事件监听器以等待加载DOM内容。