繁体   English   中英

如何使用Javascript切换或取消按钮onclick

[英]How to toggle or unpress Button onclick using Javascript

我有六个onclick按钮的表格(3x2)。 当我按下一个按钮时,在按下的按钮下方会出现一个带有一些文本的窗口。 窗口(或div)将一直显示,直到我再次按下相同的按钮。 即使我按下另一个按钮,该按钮下方也会显示另一个窗口。

我的问题是:有没有一种方法可以使其在按钮之间“切换”。 就是说,如果我按下一个按钮,则会出现一个窗口(div),如果我按下另一个按钮,则先前的窗口(div)会消失,并出现一个新的窗口?

<button onclick="myFunction(1)">Button1</button>
<div id="myDIV1" style="display:none">
"the window with text to be shown"
</div>

<button onclick="myFunction(2)">Button2</button>
<div id="myDIV2" style="display:none">
"the window with text to be shown"
</div>

<script>
function myFunction(num) {
    var str1= "myDIV"
    var str2 = num.toString();
    var result = str1 + str2
    var x = document.getElementById(result);
    if (x.style.display === "block") {
        x.style.display = "none";
    } else {
        x.style.display = "block";
    }
}
</script>

我认为在纯Javascript中,当您要使另一个按钮生效时,您需要将所有其他按钮的显示类型再次设置为none。

根据HTML的结构,您可以使用nextElementSibling所单击按钮的下一个div元素:

 function myFunction(btn) { document.querySelectorAll('button + div').forEach(function(d){ d.style.display = 'none'; // hide all }); btn.nextElementSibling.style.display = 'block'; // show div only next to the button clicked } 
 button{ display: block; margin: 10px; } button+div{ display:none; } 
 <button type="button" onclick="myFunction(this)">Button1</button> <div id="myDIV1"> "the window with text to be shown" </div> <div id=""> .....1111 </div> <button type="button" onclick="myFunction(this)">Button2</button> <div id="myDIV2"> "the window 2 with text to be shown" </div> <div id=""> .....2222 </div> 

您可以隐藏所有div,然后在按钮下方显示div。 例:

getElementsByTagName("div").style.display = "none";
x.style.display = "block";

如果您需要处理大量要切换的元素,则可能有效的解决方案是存储先前切换的html元素ref,如果用户单击另一个按钮,则将其隐藏。

 var previouslyToggled function myFunction(num) { var result = "myDIV" + num.toString(); var x = document.getElementById(result); if (previouslyToggled && previouslyToggled !== x) { previouslyToggled.style.display = 'none'; } if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } // Store element ref previouslyToggled = x } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <button onclick="myFunction(1)">Button1</button> <div id="myDIV1" style="display:none"> "the window with text to be shown for btn 1" </div> <button onclick="myFunction(2)">Button2</button> <div id="myDIV2" style="display:none"> "the window with text to be shown for btn 2" </div> </body> </html> 

暂无
暂无

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

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