具有类的单击功能仅适用于当前选择

时间:2019-07-03 13:16:17

标签: javascript jquery html click

在使点击功能按我预期的方式工作时,我遇到了一些困难。当用户单击目录名称旁边的箭头时,subViewBoxExpand仅针对该特定选择出现。

有人看到我在做什么吗?

$('.arrow').click(function() {
  var i = $(this).next('.subViewBoxExpand'),
    t = $(this).addClass('active');
  i.toggleClass('active', !0).slideToggle(500).find('.subViewBoxExpand').animate({
    opacity: 1
  }, 1500) + t, $('.subViewBoxExpand').not(i, t).slideUp(800).prev().removeClass('active');
  //$('.subViewBoxExpand').toggleClass('active');
});
.subViewBoxExpand {
  display: none;
}

.subViewBoxExpand.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog A</span><span class="arrow"> ></span>
  <div id="totalProfileViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog B</span><span class="arrow"> ></span>
  <div id="totalFastViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

  1. 使用.closest()并与.find()组合以获取selected/clicked元素及其相应的视图框。

注意:视图框不在单击的元素旁边

样本:$(this).closest('.catalogSubViewBox').find('.subViewBoxExpand')

更新:删除也在视图中切换的活动类

$('.arrow').click(function() {
  var i = $(this).closest('.catalogSubViewBox').find('.subViewBoxExpand'),
    t = $(this).addClass('active');
  i.slideToggle(500).find('.subViewBoxExpand').animate({
    opacity: 1
  }, 1500) + t, $('.subViewBoxExpand').not(i).slideUp(800).prev().prev().removeClass('active');
  //$('.subViewBoxExpand').toggleClass('active');
});
.subViewBoxExpand {
  display: none;
}

.subViewBoxExpand.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog A</span><span class="arrow"> ></span>
  <div id="totalProfileViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog B</span><span class="arrow"> ></span>
  <div id="totalFastViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>