【发布时间】:2019-09-12 00:16:52
【问题描述】:
我有一个包含 5 个按钮的按钮组。我想要按钮的 onclick 事件来切换 5 个不同的 div。单击按钮 1 打开/关闭 div 1,单击按钮 2 打开/关闭 div 2,依此类推。 div 在这里只是文本。
第一次点击按钮 --> 显示 div 第二次点击按钮 --> 隐藏 div
但是,当我只单击一个按钮并显示它的 div 并单击另一个按钮时,另一个 div 堆叠在第一个 div 之上。如果我单击它的按钮两次,我可以关闭第一个 div,但我希望即使单击不同的按钮也能关闭 div。我怎样才能做到这一点?
到目前为止,我已经附加了 jsfiddle。
我多次看到类似的问题,但似乎没有一个解决方案适合我。任何帮助将不胜感激。
function togglediv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
<div class="myButtons">
<div class="btn-group" id="MatchingEntitiesButtons">
<button id="Button1" class="roundBtns" onclick="togglediv('NamesTable')" type="button" > List of Names </button>
<button id="Button2" class="roundBtns" onclick="togglediv('PhoneTable')" type="button"> List of Address </button>
<button id="Button3" class="roundBtns" onclick="togglediv('AddressTable')" type="button" > List of Phone#</button>
<button id="Button4" class="roundBtns" onclick="togglediv('GradesTable')" type="button"> List of Grades</button>
<button id="Button5" class="roundBtns" onclick="togglediv('SchoolTable')" type="button"> List of Schools </button>
</div>
</div>
<div id ="NamesTable" class="TableBody" style="display:none">Names </div>
<div id ="PhoneTable" class="TableBody" style="display:none">Address </div>
<div id ="AddressTable" class="TableBody" style="display:none">Phone# </div>
<div id ="GradesTable" class="TableBody" style="display:none">Grades </div>
<div id ="SchoolTable" class="TableBody" style="display:none">School </div>
【问题讨论】:
标签: javascript jquery html