繁体   English   中英

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

[英]Why I can't define a DOM element as a global variable?

我正在处理表单,并想使用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>

拜托,我在做什么错?

您可以使用相同的内容。 这不成问题。 如果仍然出现null错误,建议将脚本添加到文档末尾或将其包含在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"/> 

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>最后

您可以在关闭<body>标记之前将脚本放到最后,也可以按照@jafarbtech的建议进行操作并添加事件侦听器,以等待DOM内容加载。

暂无
暂无

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

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