繁体   English   中英

如何将 HTML 元素分配给 JavaScript 全局变量?

[英]How to assign a HTML element to a JavaScript global variable?

我想知道为什么我不能将全局变量与 HTML 元素一起使用。

我正在尝试做这样的事情:

<script>
//I want to declare my variables here
  var div1 = document.getElementById('a');
  var div2 = document.getElementById('b');
  var div3 = document.getElementById('c');

 //And I want to use them here, inside a function. 
  function myFunction(){
    div1.style.display = 'none';
    div2.style.display = 'none'; 
    div3.style.display = 'none';  
  }
</script>

不知何故,它不允许我使用我在 function 之外声明的变量,但如果我这样做,它允许我:

<script>
function myFunction(){
  var div1 = document.getElementById('a');
  var div2 = document.getElementById('b');
  var div3 = document.getElementById('c');
  div1.style.display = 'none';
  div2.style.display = 'none'; 
  div3.style.display = 'none';  
}
</script>

问题是,我有很多类似的函数,我不想每次都在我创建的函数中声明变量,有没有办法将全局变量分配给 HTML 元素,这样我就可以实现我想要的第一个片段?

谢谢!

您可能在代码中做错了什么,这只是正确的方法

签出这个例子

 //I want to declare my variables here var div1 = document.getElementById('a'); var div2 = document.getElementById('b'); var div3 = document.getElementById('c'); //And I want to use them here, inside a function. function hide() { div1.style.display = 'none'; div2.style.display = 'none'; div3.style.display = 'none'; } function show() { div1.style.display = 'block'; div2.style.display = 'block'; div3.style.display = 'block'; }
 p { text-align: center; font-size: 60px; margin-top: 0px; }
 <p id="demo"></p> <input type="text" id="a"> <input type="text" id="b"> <input type="text" id="c"> <input type="button" value="hide" onclick="hide()"> <input type="button" value="show" onclick="show()">

在 JSfiddle 链接工作示例中检查相同内容

暂无
暂无

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

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