我有多个容器(li)。里面有链接。单击时,需要打开匹配的div(并隐藏不匹配的div)。
我可以遍历div但无法打开或隐藏它们。
Codepen:https://codepen.io/warddem/pen/kkzrPx
<ul>
<li>
<h3>Market study</h3>
<div>
<a href="#" data-toggle="#div1" class="showSingle">Results</a>
<a href="#" data-toggle="#div2" class="showSingle">Learned</a>
<a href="#" data-toggle="#div3" class="showSingle">Deliverables</a>
<a href="#" data-toggle="#close" class="">Close all</a>
<div id="div1" class="optionDiv">Results: </div>
<div id="div2" class="optionDiv">Learned: </div>
<div id="div3" class="optionDiv">Deliverables: </div>
</div>
</li>
<li>
<h3>Competitive research</h3>
<div>
<a href="#" data-toggle="#div1" class="showSingle">Results</a>
<a href="#" data-toggle="#div2" class="showSingle">Learned</a>
<a href="#" data-toggle="#div3" class="showSingle">Deliverables</a>
<a href="#" data-toggle="#close" class="">Close all</a>
<div id="div1" class="optionDiv">Results: </div>
<div id="div2" class="optionDiv">Learned: </div>
<div id="div3" class="optionDiv">Deliverables: </div>
</div>
</li>
</ul>
jQuery('.showSingle').click(function() {
var idOpen = $(this).siblings("div");
var myIndex = $(this).index();
if (idOpen.is("div")) {
// HIDE ALL DIVS IN PARENT
var divLength = idOpen.get(myIndex).id.length;
for (var i = 0, l = divLength; i < l; i++) {
console.log('divs to hide', idOpen[i]);
//HIDE DOESN'T WORK
//idOpen[i].hide();
}
// HOW TO SHOW LINKED DIV ???
console.log('div id to open: ', idOpen.get(myIndex).id);
}
})
答案 0 :(得分:1)
从使id唯一开始。 (虽然这似乎与您遇到的问题无关。)
.get()
将元素作为元素返回。 jQuery函数不会链接到这些。 .eq()
将元素作为新jQuery对象的一部分返回。
<ul>
<li>
<h3>Market study</h3>
<div>
<a href="#" data-toggle="#div1a" class="showSingle">Results</a>
<a href="#" data-toggle="#div2a" class="showSingle">Learned</a>
<a href="#" data-toggle="#div3a" class="showSingle">Deliverables</a>
<a href="#" data-toggle="#close" class="">Close all</a>
<div id="div1a" class="optionDiv">Results: </div>
<div id="div2a" class="optionDiv">Learned: </div>
<div id="div3a" class="optionDiv">Deliverables: </div>
</div>
</li>
<li>
<h3>Competitive research</h3>
<div>
<a href="#" data-toggle="#div1b" class="showSingle">Results</a>
<a href="#" data-toggle="#div2b" class="showSingle">Learned</a>
<a href="#" data-toggle="#div3b" class="showSingle">Deliverables</a>
<a href="#" data-toggle="#close" class="">Close all</a>
<div id="div1b" class="optionDiv">Results: </div>
<div id="div2b" class="optionDiv">Learned: </div>
<div id="div3b" class="optionDiv">Deliverables: </div>
</div>
</li>
</ul>
jQuery('.showSingle').click(function() {
var idOpen = $(this).siblings("div");
var myIndex = $(this).index();
if (idOpen.is("div")) {
// HIDE ALL DIVS IN PARENT
var divLength = idOpen.get(myIndex).id.length;
for (var i = 0, l = divLength; i < l; i++) {
console.log('divs to hide', idOpen[i]);
//HIDE DOESN'T WORK
idOpen.eq(i).hide();
}
// HOW TO SHOW LINKED DIV ???
idOpen.eq(myIndex).show();
console.log('div id to open: ', idOpen.get(myIndex));
}
});