简体   繁体   English

如何使用JavaScript进行开/关切换?

[英]How to make an on/off switch using javascript?

so when a user clicks on a link a specific element should be shown and when the user clicks that link again the element should hide.I m trying do it but there's a problem with my code.It occurs just once.I want to occur for infinite times.Can anyone help? 所以当用户点击链接时,应该显示一个特定的元素,当用户再次点击该链接时,该元素应该隐藏。无限次。有人可以帮忙吗?

 <html> <head> <style> #test { width: 200px; height: 200px; background-color: black; display: none; } </style> </head> <body> <script type="text/javascript"> window.onload = function() { var yes = 10; for (i = 0; i < 100; i++) { if (yes == 10) { document.getElementById("test1").onclick = function() { document.getElementById("test").style.cssText = "display:block;" yes = yes + 1; if (yes == 11) { document.getElementById("test1").onclick = function() { document.getElementById("test").style.cssText = "display:none;" yes = yes - 1; } } } } } } </script> <a id="test1" href="#">link</a> <div id="test"></div> </body> </html> 

You should set onclick only once. 您只能将onclick设置一次。

Write the function so that it will first check if the element is visible, and either show it or hide it. 编写函数,以便它首先检查元素是否可见,然后显示或隐藏它。

(Also you can use .style.display rather than .style.cssText ) (也可以使用.style.display而不是.style.cssText

You are doing way more work than you need to do. 您正在做的事情比您需要做的更多。

Simply check if the div is currently displayed, if it is, hide it, if it isn't show it. 只需检查div是否当前显示(如果显示),将其隐藏(如果未显示)。

Your script tag can be reduced to: 您的脚本标签可以减少为:

<script>
  document.getElementById('test1').addEventListener('click', function() {
    var theDiv = document.getElementById('test');

    if(theDiv.style.display === 'block') {
      theDiv.style.display = 'none';
    } else {
      theDiv.style.display = 'block';
    }
  });
</script>

Not sure why you're doing the loop, but here's how you can do the click part with just one listener: 不确定为什么要执行循环,但是这是仅用一个侦听器即可完成click部分的方法:

 var el = document.getElementById("test"); document.getElementById("test1").onclick = function() { if (el.style.display == "block") { el.style.display = "none"; } else { el.style.display = "block"; } } 
 #test { width: 200px; height: 200px; background-color: black; display: none; } 
 <a id="test1">link</a> <div id="test"></div> 

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

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