在循环中查找特定div并添加类

时间:2017-03-06 13:17:26

标签: jquery

当然有人可以很快回答这个问题!我有一些html标记,它是一个类似div的循环,每个div都有一个显示/隐藏div本身的按钮。我正在努力与jQuery找到最近的“目标div”来切换它的显示类。

因此,对于每个“companyItemWrapper”,当用户点击其中的“execSummaryLink”按钮时 - 它应该切换最近的“companyItemWrapperOverlayWrapper”div的类

示例代码是:

<div class="companyItemWrapper">
<h3>Company Name</h3>
<p><a href="#" title="Latest executive summary" class="execSummaryLink">Latest executive summary</a></p>

<!-- OVERLAY -->
<div class="companyItemWrapperOverlayWrapper">
<p>content...</p>
</div>
<!-- end of OVERLAY -->

</div>
<!-- end of COMPANY ITEM -->

<div class="companyItemWrapper">
<h3>Company Name</h3>
<p><a href="#" title="Latest executive summary" class="execSummaryLink">Latest executive summary</a></p>

<!-- OVERLAY -->
<div class="companyItemWrapperOverlayWrapper">
<p>content...</p>
</div>
<!-- end of OVERLAY -->

</div>
<!-- end of COMPANY ITEM -->

<div class="companyItemWrapper">
<h3>Company Name</h3>
<p><a href="#" title="Latest executive summary" class="execSummaryLink">Latest executive summary</a></p>

<!-- OVERLAY -->
<div class="companyItemWrapperOverlayWrapper">
<p>content...</p>
</div>
<!-- end of OVERLAY -->

</div>
<!-- end of COMPANY ITEM -->

3 个答案:

答案 0 :(得分:3)

尝试此解决方案。

&#13;
&#13;
$('.execSummaryLink').click(function() {
  $(this).parents(".companyItemWrapper").find(".companyItemWrapperOverlayWrapper").toggle()
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="companyItemWrapper">
<h3>Company Name</h3>
<p><a href="#" title="Latest executive summary" class="execSummaryLink">Latest executive summary</a></p>

<!-- OVERLAY -->
<div class="companyItemWrapperOverlayWrapper">
<p>content...</p>
</div>
<!-- end of OVERLAY -->

</div>
<!-- end of COMPANY ITEM -->

<div class="companyItemWrapper">
<h3>Company Name</h3>
<p><a href="#" title="Latest executive summary" class="execSummaryLink">Latest executive summary</a></p>

<!-- OVERLAY -->
<div class="companyItemWrapperOverlayWrapper">
<p>content...</p>
</div>
<!-- end of OVERLAY -->

</div>
<!-- end of COMPANY ITEM -->

<div class="companyItemWrapper">
<h3>Company Name</h3>
<p><a href="#" title="Latest executive summary" class="execSummaryLink">Latest executive summary</a></p>

<!-- OVERLAY -->
<div class="companyItemWrapperOverlayWrapper">
<p>content...</p>
</div>
<!-- end of OVERLAY -->

</div>
<!-- end of COMPANY ITEM -->
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$(". execSummaryLink").on("click",function(){
    event.preventDefault();
    $(this).parent(".companyItemWrapper").find(". companyItemWrapperOverlayWrapper").toggleClass("anotherClass");
});

应该这样做。

答案 2 :(得分:0)

$(".execSummaryLink").click(function(event) {
    event.preventDefault();
    $(this).closest('.companyItemWrapper').find('.companyItemWrapperOverlayWrapper').toggleClass('XXXX');
})