[英]How to show/hide a div in javascript?
When i click the button i want the div to show, and when i click the button again i want it to disappear. 当我单击按钮时,我希望div显示,当我再次单击按钮时,我希望它消失。 What am i doing wrong?
我究竟做错了什么?
<button type="button" onclick="myFunction()">Click Me!</button> <div id="Dglow" class="Dglow"> Glow </div> <script> function myFunction() { var e = document.getElementById("Dglow").style.display; if (e == "none") e = "block"; else { e = "none"; } }
You should compare and change element's display
property: 您应该比较并更改元素的
display
属性:
function myFunction() { var e = document.getElementById("Dglow").style; if (e.display == "none") { e.display = "block"; } else { e.display = "none"; } }
<button type="button" onclick="myFunction()">Click Me!</button> <div id="Dglow" class="Dglow">Glow</div>
Actually document.getElementById("Dglow").style.display
returns a string and according to Left hand assignment rule you cannot store anything to that string, since that string is not a variable/object now ie not a reference to DOM anymore 实际上,
document.getElementById("Dglow").style.display
返回一个字符串,根据左手分配规则,您无法将任何内容存储到该字符串,因为该字符串现在不再是变量/对象,即不再是对DOM的引用
You can do is 你可以做的是
var e = document.getElementById("Dglow").style;
if(e.display == "none")
e.display = "block";
else{
e.display = "none";
}
Have you considered using Jquery? 您是否考虑过使用Jquery? If so heres what you need.
如果是这样,那么您需要什么。
$(document).ready(function(){
$("#button").click(function(){
$("#Dglow").toggle();
});
});
You would need to give your button an id for this though. 不过,您需要为此按钮指定一个ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.