jQuery:每次点击只显示一个项目

时间:2016-05-05 02:58:06

标签: jquery css

我有小问题,也许你可以帮我吗? 我有HTML div并显示和隐藏功能。

我只希望每次点击显示一(1)div,而不是全部。 我制作了一个jquery代码,但它显示了所有div。

需要建议。

https://jsfiddle.net/pfcglen/pLfbwve5/2/

jQuery(document).ready(function() {

    var toggleContent = jQuery('.insideContent');
    toggleContent.addClass('hidden');
    var thisElemnt = $(this);
    jQuery('.button').on('click', function() {
        thisElemnt.find('.insideContent').removeClass('hidden').addClass('show');
    });


});



jQuery(document).ready(function() {

  var toggleContent = jQuery('.insideContent');
  toggleContent.addClass('hidden');
  var thisElemnt = $(this);
  jQuery('.button').on('click', function() {
    thisElemnt.find('.insideContent').removeClass('hidden').addClass('show');
  });


});

.hidden {
  display: none !important;
}
.show {
  display: block !important;
}
.list {
  direction: inherit;
  display: flex;
  width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="list">
  <div class="col-lg-2 workImage">
    <div class="itemTitle">
      <h2 class="page-header  text-center">Item</h2>
      <button class="button">Open Project</button>
    </div>
    <div class="insideContent">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
  <div class="col-lg-2 workImage">
    <div class="itemTitle">
      <h2 class="page-header  text-center">Item</h2>
      <button class="button">Open Project</button>
    </div>
    <div class="insideContent">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
  <div class="col-lg-2 workImage">
    <div class="itemTitle">
      <h2 class="page-header  text-center">Item</h2>
      <button class="button">Open Project</button>
    </div>
    <div class="insideContent">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

jQuery(document).ready(function() {

    var toggleContent = jQuery('.insideContent');
    toggleContent.addClass('hidden');
    var thisElemnt = $(this);
    jQuery('.button').on('click', function() {
        $(this).closest('.itemTitle').next('.insideContent').toggleClass('hidden show');//use $(this) to apply only to click elemt
    });


});

然后使用.closest()获取最近的父.itemtitle 然后使用.next()获取目标div 使用.toggleClass()显示和隐藏目标div

DEMO