【发布时间】:2023-03-18 05:50:01
【问题描述】:
我有一个包含六个 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 html function button onclick