[英]Uncaught TypeError: Cannot read property 'style' of null
My code seems to have a problem that I don't know how to fix. 我的代码似乎有一个我不知道如何解决的问题。 I'm extremely new to this stuff and have almost no idea what I'm doing. 我对这些东西非常陌生,几乎不知道我在做什么。 Every time I run my code this error pops up. 每次我运行代码时,都会弹出此错误。 I'm trying to make when you click the button the blue box disappears. 我试图使您单击按钮时蓝色框消失。 And when you click the button again the blue box reappears and the green box disappears. 当您再次单击该按钮时,蓝色框再次出现,绿色框消失。 Here's my code: 这是我的代码:
<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>
You need to add quotation marks to the arguments of the function: 您需要在函数的参数中添加引号:
<button onclick="toggle_visibility('greenbox','bluebox')">Pls Work</button>
They are not variables, they are strings. 它们不是变量,而是字符串。
You have to pass the id
's of both elements to the function as strings . 您必须将两个元素的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>
The parameter id
is not passed correctly from the HTML, you need to pass the ID correctly like onclick="toggle_visibility('greenbox','bluebox')"
无法从HTML正确传递参数id
,您需要像onclick="toggle_visibility('greenbox','bluebox')"
一样正确传递ID。
Following code should work for you. 以下代码将为您工作。
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'; } }
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.