【问题标题】:Hide/ show the div element of same class name when a button is clicked单击按钮时隐藏/显示具有相同类名的 div 元素
【发布时间】:2016-08-17 16:46:38
【问题描述】:

在这里,我想在单击 box1 内的按钮时隐藏或显示 box2 和 box3。类框也是动态重复的次数。因此,每当我单击按钮时,它必须隐藏/显示与该特定类框关联的类 box2 和 box3,而是显示所有类中的 box2 和 box3 元素。请帮我。如果您可以使用此关键字解决此问题,那就更好了。谢谢你。下面是我的html和jquery代码。

$(document).ready(function() {
  $(".box2").hide();
  $(".box3").hide();

  $('.see').click(function() {
    var value = $(this).attr('value');
    $('.box2').toggle('fast');
    $('.box3').toggle('fast');

    if (value == 'See More') {
      $(this).attr('value', 'See Less');
    } else if (value == 'See Less') {
      $(this).attr('value', 'See More');
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="Box">
  <div class="box1">
    <input type="button" class="see" value="See More" />
  </div>
  <div class="box2">
  </div>
  <hr />
  <div class="box3">
  </div>
</div>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    使用$(this).closest(".Box") 查找包含单击按钮的框。从那里您可以在同一个框中找到.box2.box3

    另外,使用.val() 获取和设置元素的值。

    $(document).ready(function() {
      $(".box2, .box3").hide();
    
      $('.see').click(function() {
        $(this).closest(".Box").find(".box2, .box3").toggle('fast');
        $(this).val(function(i, value) {
          return value == 'See More' ? 'See Less' : 'See More';
        });
    
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="Box">
      <div class="box1">
        <input type="button" class="see" value="See More" />
      </div>
      <div class="box2">
        Box 2
      </div>
    
      <hr />
      <div class="box3">
        Box 3
      </div>
    </div>
    
    <hr style="height: 2px; border: none; background-color: #000;">
    
    <div class="Box">
      <div class="box1">
        <input type="button" class="see" value="See More" />
      </div>
      <div class="box2">
        Box 2
      </div>
    
      <hr />
      <div class="box3">
        Box 3
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 2013-01-16
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多