我有一个带有 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>
循环遍历所有 DIV。如果是指定的 DIV,则切换它,否则隐藏它。
function togglediv(id) {
document.querySelectorAll(".TableBody").forEach(function(div) {
if (div.id == id) {
// Toggle specified DIV
div.style.display = div.style.display == "none" ? "block" : "none";
} else {
// Hide other DIVs
div.style.display = "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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句