我试图隐藏任何 <div>
没有 <ul>
具有特定的ID。我有一个 fiddle ,我正在尝试这个,但它没有按我预期的方式工作。我可以将它们全部隐藏,但我想继续显示的那个不起作用。
HTML
<ul id="accordion">
<li>
<div style="background-color: rgb(109, 129, 27);" class="expand" title="Click to Expand">Zoos</div>
<ul class="sortCat1" id="zoo">
<li id="1"><a href="#">1</a></li>
<li id="2"><a href="#">2</a></li>
<li id="3"><a href="#">3</a></li>
</ul>
</li>
<li>
<div style="background-color: rgb(109, 129, 27);" title="Click to Expand" class="expand">Attractions</div>
<ul class="sortCat2" id="attractions">
<li id="1"><a href="#">1</a></li>
<li id="2"><a href="#">2</a></li>
<li id="3"><a href="#">3</a></li>
</ul>
</li>
<li>
<div style="background-color: rgb(109, 129, 27);" title="Click to Expand" class="expand">Dining & Shopping</div>
<ul class="sortCat3" id="dinShop">
<li id="1"><a href="#">1</a></li>
<li id="2"><a href="#">2</a></li>
<li id="3"><a href="#">3</a></li>
</ul>
</li>
</ul>
Javascript
if($('.expand ul').id == 'attractions'){
$(this).css({'display': 'block'});
}else{
$('.expand').css({'display': 'none'});
}
JSFiddle http://jsfiddle.net/27Wmm/
最佳答案
讨论数字 id 的非优点...
从字里行间我认为你想要这样的东西(切换打开与标记的 div 关联的 UL):
JSFiddle:http://jsfiddle.net/TrueBlueAussie/27Wmm/1/
$(function () {
$('#accordion').on('click', '.expand', function () {
var $this = $(this);
// Show the sibling of the clicked div
$this.next().css({
'display': 'inherit'
});
// Now hide all others sibling of the non-clicked divs
$('.expand').not($this).next().css({
'display': 'none'
});
});
});
对于任何类型的菜单,您通常希望避免对选择进行任何硬编码,并使其对单击的项目(以及未单击的其他相关项目)进行操作。
您可能还只想启动一个(如果有的话)未折叠的,这仅意味着它们的初始样式。例如在CSS中
#accordion ul {
display: none;
}
JSFiddle:http://jsfiddle.net/TrueBlueAussie/27Wmm/3/
更新
如果您希望它具有特定的启动行为,您可以提取出执行该工作的位并在启动时调用它。
JSFiddle:http://jsfiddle.net/TrueBlueAussie/27Wmm/4/
var showThis = function ($this) {
// Show the sibling of the clicked div
$this.next().css({
'display': 'inherit'
});
// Now hide all others
$('.expand').not($this).next().css({
'display': 'none'
});
}
$(function () {
$('#accordion').on('click', '.expand', function () {
showThis($(this));
});
showThis($('#attractions').prev());
});
另一个更新
根据评论,所需的行为是简单地显示景点 DIV 和关联的 UL。如果是这样的话(我仍然有疑问)你会将上面的内容更改为:
var showThis = function ($this) {
// Show the div, then show the sibling of the clicked div
$this.css({
'display': 'inherit'
}).next().css({
'display': 'inherit'
});
// Now hide all other divs and ULs
$('.expand').not($this).css({
'display': 'none'
}).next().css({
'display': 'none'
});
}
$(function () {
showThis($('#attractions').prev());
});
JSFiddle:http://jsfiddle.net/TrueBlueAussie/27Wmm/5/
这应该足够玩了。
关于javascript - 如何使用 jQuery 隐藏具有特定 id 的 ul 的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23617431/