未捕获的TypeError:无法读取null的属性'style'

时间:2017-02-09 17:28:07

标签: javascript jquery html css

我的代码似乎有一个我不知道如何修复的问题。我对这些东西非常陌生,几乎不知道我在做什么。每次运行我的代码时,都会弹出此错误。我想点击按钮时蓝色框消失。当您再次单击该按钮时,蓝色框重新出现,绿色框消失。这是我的代码:

<script type="text/javascript">
   function toggle_visibility(id1,id2){
   var e1 = document.getElementById(id1);
   var e2 = document.getElementById(id2);

   if (e1.style.visibility == 'hidden') {
      e1.style.visibility = 'visible';
      e2.style.visibility = 'visible';}
      else{
      e1.style.visibility = 'hidden';
      e2.style.visibility = 'hidden';
      }
      }
</script>
<div class="square" id="bluebox" style="visibility:visible"></div><br>
<div class="box" id="greenbox" style="visibility:visbible"></div><br>
<button onclick=" toggle_visibility(greenbox,bluebox)">Pls Work</button>

3 个答案:

答案 0 :(得分:0)

您需要在函数的参数中添加引号:

<button onclick="toggle_visibility('greenbox','bluebox')">Pls Work</button>

它们不是变量,而是字符串。

答案 1 :(得分:0)

您必须将两个元素的id作为字符串传递给函数。

function toggle_visibility(id1, id2) {
     var e1 = document.getElementById(id1);
     var e2 = document.getElementById(id2);

     if (e1.style.visibility == 'hidden') {
       e1.style.visibility = 'visible';
       e2.style.visibility = 'visible';
     } else {
       e1.style.visibility = 'hidden';
       e2.style.visibility = 'hidden';
     }
   }
.square, .box {
  height: 50px;
  width: 50px;
  visibility: hidden;
}

#greenbox {
  background-color: green;
}

#bluebox {
    background-color: blue;
}
<div class="square" id="bluebox"></div>
<br>
<div class="box" id="greenbox"></div>
<br>
<button onclick="toggle_visibility('bluebox', 'greenbox')">Pls Work</button>

答案 2 :(得分:0)

参数id未正确传递来自HTML,您需要像onclick="toggle_visibility('greenbox','bluebox')"

一样正确传递ID

以下代码应该适合您。

&#13;
&#13;
   function toggle_visibility(id1,id2){
   var e1 = document.getElementById(id1);
   var e2 = document.getElementById(id2);

   if (e1.style.visibility == 'hidden') {
      e1.style.visibility = 'visible';
      e2.style.visibility = 'visible';}
      else{
      e1.style.visibility = 'hidden';
      e2.style.visibility = 'hidden';
      }
      }
&#13;
<div class="square" id="bluebox" style="visibility:visible"></div><br>
<div class="box" id="greenbox" style="visibility:visbible"></div><br>
<button onclick="toggle_visibility('greenbox','bluebox')">Pls Work</button>
&#13;
&#13;
&#13;