jQuery显示/隐藏 - 添加/删除.active类

时间:2017-04-21 10:26:01

标签: jquery

这可能已被问过好几次,但我有点挣扎。希望有人能提供帮助。 HTML&下面的jQuery,只想添加类' .active' div打开时按钮,关闭时删除.active。



jQuery(function() {
  jQuery('.expand').on('click', function(e) {
    e.preventDefault();
    var href = jQuery(this).attr("data-href");
    jQuery("#" + href).slideToggle('slow', function() {

    }).siblings('div.expanded').hide();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-lg-10">
    <strong>Short Description</strong>
  </div>
  <div class="col-lg-2">
    <a data-href="one" href="#" class="expand btn btn-primary btn-sm">more...</a> &nbsp;
  </div>
</div>
<div id="one" style="display: none;" class="expanded row">
  <strong>Long Description</strong>
</div>

<div class="row">
  <div class="col-lg-10">
    <strong>Short Description</strong>
  </div>
  <div class="col-lg-2">
    <a data-href="two" href="#" class="expand btn btn-primary btn-sm">more...</a> &nbsp;
  </div>
</div>
<div id="two" style="display: none;" class="expanded row">
  <strong>Long Description</strong>
</div>

<div class="row">
  <div class="col-lg-10">
    <strong>Short Description</strong>
  </div>
  <div class="col-lg-2">
    <a data-href="three" href="#" class="expand btn btn-primary btn-sm">more...</a> &nbsp;
  </div>
</div>
<div id="three" style="display: none;" class="expanded row">
  <strong>Long Description</strong>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

要执行此操作,您可以使用toggleClass()方法在单击的元素上连续添加和删除类。试试这个:

jQuery(function($) {
  jQuery('.expand').on('click', function(e) {
    e.preventDefault();
    var href = $(this).data("href");
    $("#" + href).slideToggle('slow').siblings('div.expanded').hide();
    $('.active').not(this).removeClass('active');
    $(this).toggleClass('active');
  });
});
.expanded.row { display: none; }
.active { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-lg-10">
    <strong>Short Description</strong>
  </div>
  <div class="col-lg-2">
    <a data-href="one" href="#" class="expand btn btn-primary btn-sm">more...</a> &nbsp;
  </div>
</div>
<div id="one" class="expanded row">
  <strong>Long Description</strong>
</div>

<div class="row">
  <div class="col-lg-10">
    <strong>Short Description</strong>
  </div>
  <div class="col-lg-2">
    <a data-href="two" href="#" class="expand btn btn-primary btn-sm">more...</a> &nbsp;
  </div>
</div>
<div id="two" class="expanded row">
  <strong>Long Description</strong>
</div>

<div class="row">
  <div class="col-lg-10">
    <strong>Short Description</strong>
  </div>
  <div class="col-lg-2">
    <a data-href="three" href="#" class="expand btn btn-primary btn-sm">more...</a> &nbsp;
  </div>
</div>
<div id="three" class="expanded row">
  <strong>Long Description</strong>
</div>