jQuery与相同的类一一切换div

时间:2019-11-25 02:15:21

标签: javascript jquery html toggle

当我点击链接时,我想一一切换showhide格。我尝试了find() next()来定位div。但无法达到预期的效果。帮我实现这个目标。

为进一步澄清,请删除您的评论。

$(document).ready(function() {
  $('.showhide').hide();
  $('.divider a').click(function(e) {
    e.preventDefault();
    //$(".showhide").slideToggle();
    $(this).parent().next().find(".showhide").slideToggle();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="link">
    <div class="divider">
        <a href="#">Link 1</a>
    </div>
     <div class="divider">
        <a href="#">Link 2</a>
    </div>
    <div class="divider">
        <a href="#">Link 3</a>
    </div>
</div>
<div class="link-content">
    <div class="divider-desc">
        <div class="showhide">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
        </div>
        <div class="showhide">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
        </div>
        <div class="showhide">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
        </div>
    </div>
</div>

3 个答案:

答案 0 :(得分:2)

您需要按索引选择。使用insertVar来选择一个。

.eq()
$(document).ready(function() {
      $('.showhide').hide();
      $('.divider').click(function(e) {  // note the change here
        e.preventDefault();
        $(".showhide").eq($(this).index()).slideToggle(); // and selector here with .eq
      });
    });

答案 1 :(得分:0)

Try below code:

$(document).ready(function() {
    $('.showhide').hide();
    $('.divider a').click(function(e) {
      e.preventDefault();
      //$(".showhide").slideToggle();
      $(this).parent().parent().next().find(".showhide").slideToggle();
      console.log($(this).parent().parent().next().find(".showhide"))
    });
  });

答案 2 :(得分:0)

您可以一次从each循环中获取被单击元素的索引:

$('.divider a').each(function(index){
  $(this).on('click', function(e){
    $('.showhide').eq( index ).toggle();
    $(this).toggleClass('active'); // just to indicate the opened links
    e.preventDefault();
  });
});
.showhide { display: none; margin: 5px; }
a.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divider"><a href="https://stackoverflow.com/questions/59024393/jquery-toggle-div-one-by-one-with-the-same-class#" target="_blank">Link 1</a></div>
<div class="divider"><a href="#">Link 2</a></div>
<div class="divider"><a href="#">Link 3</a></div>

<div class="showhide">1111</div>
<div class="showhide">2222</div>
<div class="showhide">3333</div>