我正在尝试为此脚本添加一个循环,以便在我按下其中一个后隐藏所有其他div:
function showHideDiv(id) {
var obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = 'block';
} else if (obj.style.display == "block") {
obj.style.display = 'none';
}
}
<li style="opacity: 1; transform: matrix(1, 0, 0, 1, 0, 0);"><a href="#guitars" onclick="showHideDiv('guitars')">Guitars</a>
</li>
<li style="opacity: 1; transform: matrix(1, 0, 0, 1, 0, 0);"><a href="#basses" onclick="showHideDiv('basses')">Basses</a>
</li>
<li style="opacity: 1; transform: matrix(1, 0, 0, 1, 0, 0);"><a href="#gallary" onclick="showHideDiv('gallary')">GALLLARY</a>
</li>
<div id="guitars" class="guitars" style="display: none;" class="mCustomScrollbar" data-mcs-theme="dark">
<h2>Our Guiters</h2>
</div>
<div id="guitars" class="guitars" style="display: none;" class="mCustomScrollbar" data-mcs-theme="dark">
<h2>Our Basses</h2>
</div>
答案 0 :(得分:0)
您可以这样做:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//do something to each div like
if (divs[i].style.display=="none"){
divs[i].style.display='block';
} else if(divs[i].style.display=="block"){
divs[i].style.display='none';
}
}
如果您不想选择所有div,可以将类分配给所需的div并使用该方法:
document.getElementsByClassName('assignedclass')
答案 1 :(得分:0)
如果我正确理解了您的问题,以下代码可能会对您有所帮助。
$(document).ready(function() {
var d = $('#parent > div').length;
$('#parent > div').click(function (e)
{
var s = $('#parent > div').length -1;
var z = $('div').index(this);
for(i=0;i<=(s);i++){
var y = z-1;
if(i != y){
$('#parent > div').eq(i).css('display','none');
console.log('Index '+i+'has been hidden');
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div>Guitars Basses GALLLARY</div>
<div>Our Guiters</div>
<div>Our Basses</div>
</div>