显示和隐藏具有相同类名的多个div不起作用

时间:2016-08-17 21:37:12

标签: javascript jquery html

我想显示/隐藏无数个具有相同类名的div。我为此使用JQuery。请参阅我的jsfiddle:http://jsfiddle.net/1g2hw6hh/2/

我尝试在JQuery中使用下一个选择器

$(document).ready(function() {
  $(".jsonInfo").hide(); // it's obvious
  $(".showJSON").click(function() {  // on click...

    $(".jsonInfo")
      .hide()  // ...hide all other previus opened elements...
      .eq($(this).index('.showJSON')) // ... select right one by index of clicked .showJSON element...
       .toggle(); // and show/hide it
  });
});

如何修复此问题并让div显示/隐藏?

4 个答案:

答案 0 :(得分:0)

您可以在每个按钮中添加一个值(或数据属性,如果您愿意),然后在onclick上 - 获取该值(或数据属性)并使用.eq(),显示特定的div。实际上,当您单击第一个按钮时 - 显示第一个相关div,当您单击第二个按钮时 - 隐藏可见的div并显示指定的div。这并不需要按钮的零索引编号。

您还可以通过使用循环并在将内容放入页面时使用该循环的索引来简化创建按钮的代码(如果它们都具有相同的基本结构)

$(document).ready(function() {
  $(".jsonInfo").hide();
  $(".showJSON").click(function() {
    $(".jsonInfo").hide();
    var showJsonVal = $(this).val();
    $(".jsonInfo").eq(showJsonVal).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="showJSON" value="0">Show JSON 1</button>
<button class="showJSON" value="1">Show JSON 2</button>
<button class="showJSON" value="2">Show JSON 3</button>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 1</h6>
  </div>
</div>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 2</h6>
  </div>
</div>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 3</h6>
  </div>
</div>

答案 1 :(得分:0)

如果你想显示/隐藏NEXT到按钮div - 你需要重写你的html:

<button class="showJSON">Show JSON 1</button>
<div class="jsonInfo">
<h6>JSON 1</h6>
</div>
...

但是如果你需要按钮的类隐藏,你需要像这样的东西:

<button class="showJSON" class-to-hide="jsonInfo">Show JSON 1</button>

$(document).ready(function() {
  $(".jsonInfo").hide();

    $(".showJSON").click(function() {  
      var cls = $(this).attr('class-to-hide');        
      $("div."+cls).toggle();
  });
});

答案 2 :(得分:0)

.next()选择下一个兄弟元素,它有&#34; .jsonInfo&#34;类。因为你的下一个sibilings只有按钮和div&#34; .row&#34; class,你需要使用这样的东西:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="showJSON">Show JSON 1</button>
<button class="showJSON">Show JSON 2</button>
<button class="showJSON">Show JSON 3</button>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 1</h6>
  </div>
</div>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 2</h6>
  </div>
</div>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 3</h6>
  </div>
</div>
&#13;
app-boot.js
&#13;
&#13;
&#13;

但是你需要记住,你需要以相同的顺序拥有相同数量的 button.showJSON div.jsonInfo

答案 3 :(得分:0)

如果要单独切换它们,则需要使用id或data-id。

<button id="1" class="showJSON">Show JSON 1</button>
<!-- infinitely many buttons...--> 

<div data-id="1" class="jsonInfo">
   <h6>JSON 1</h6>
</div>
<!-- infinitely many divs...-->

https://jsfiddle.net/k0fL2aho/

相关问题