我需要在同一页面上多次点击时显示/隐藏 div。每个按钮应该只影响它的子按钮。
我可以让它适用于一个容器,如下所示:
HTML:
<div class="container">
<div class="buttons">
<a class="showSingle" target="1">Div 1</a>
<a class="showSingle" target="2">Div 2</a>
<a class="showSingle" target="3">Div 3</a>
</div>
<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
</div>
JS:
jQuery(function(){
jQuery('.showSingle').click(function(){
jQuery('.targetDiv').hide();
jQuery('#div'+$(this).attr('target')).show();
});
});
但我不能用于多个容器: JSFiddle
我知道这听起来是一个愚蠢的问题,但我尝试将其包装在 each()
函数中,或使用 children()
但无法使其工作。谢谢
注意:我无法将 id 添加到容器,因为它们是动态生成的
最佳答案
为什么不将 closest()
与 find()
一起使用
closest()
将获取最近的选择器,然后您可以仅为受尊敬的父级找到所需的子级。
$('.showSingle').click(function(){
$(this).closest('.container').find('.targetDiv').hide();
$(this).closest('.container').find('#div'+$(this).attr('target')).show();
});
仅供引用,对 DOM 中的多个元素使用相同的 ID 不是好习惯,请使用类而不是 ID。
jQuery(function(){
jQuery('#showall').click(function(){
jQuery('.targetDiv').show();
});
$('.showSingle').click(function(){
$(this).closest('.container').find('.targetDiv').hide();
$(this).closest('.container').find('#div'+$(this).attr('target')).show();
});
});
.container {
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="buttons">
<a class="showSingle" target="1">Div 1</a>
<a class="showSingle" target="2">Div 2</a>
<a class="showSingle" target="3">Div 3</a>
<a class="showSingle" target="4">Div 4</a>
</div>
<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
</div>
<div class="container">
<div class="buttons">
<a class="showSingle" target="1">Div 1</a>
<a class="showSingle" target="2">Div 2</a>
<a class="showSingle" target="3">Div 3</a>
<a class="showSingle" target="4">Div 4</a>
</div>
<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
</div>
关于jQuery 单击时显示/隐藏 div,仅针对子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40176168/