使用jQuery

时间:2018-12-12 18:24:32

标签: javascript jquery

我有一个小型的自制过滤器条,用于做一些小事情。 当我单击“筛选器”按钮时,我想隐藏不在类别中的行。

当我单击“营销”时,它将隐藏所有其他类别,并且对兄弟姐妹而言都是相同的。当我按ALL时,我想再次显示所有行。

我敢肯定那里必须有更好的方法,我只是想不通

(function ($) {

  $('#FilterBar a').click(function () {
  
    if ($('#FilterBar a').is('.all')) {
        $('.row').show();
    }
    else if ($('#FilterBar a').is('.pauses')) {
        $('#Agenda .row:not(.pauses)').hide();
    }
    else if ($('#FilterBar a').is('.marketing')) {
        $('#Agenda .row:not(.marketing)').hide();
    }
    else if ($('#FilterBar a').is('.sales')) {
        $('#Agenda .row:not(.sales)').hide();
    }
  });

})(jQuery);
.wrapper {
  padding: 20px;
}
#FilterBar a {
  padding: 5px;
}
#Agenda {
  padding: 15px 5px 5px;
}
#Agenda div {
  padding: 20px;
  background: #e7e7e7;
}
#Agenda div:nth-child(even) {
  padding: 20px;
  background: #f7f7f7;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
  <div id="FilterBar">
    <a href="#all" class="all">All</a>
    <a href="#pauses" class="pauses">Pauses</a>
    <a href="#markering" class="marketing">Marketing</a>
    <a href="#sales" class="sales">Sales</a>
  </div>
  <div id="Agenda">
    <div class="row pauses"><b>Pause:</b> Break at 10:30</div>
    <div class="row marketing"><b>Marketing:</b> This is marketing</div>
    <div class="row sales"><b>Sales:</b> Sales is important</div>
  </div>
</div>

1 个答案:

答案 0 :(得分:3)

您可以这样做:

(function ($) {

  $('#FilterBar a').click(function () {
      $('#Agenda .row').hide();
      const className = $(this).attr('class');
      $('#Agenda .' + (className === 'all' ? 'row' : className)).show();
  });

})(jQuery);
.wrapper {
  padding: 20px;
}
#FilterBar a {
  padding: 5px;
}
#Agenda {
  padding: 15px 5px 5px;
}
#Agenda div {
  padding: 20px;
  background: #e7e7e7;
}
#Agenda div:nth-child(even) {
  padding: 20px;
  background: #f7f7f7;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
  <div id="FilterBar">
    <a href="#all" class="all">All</a>
    <a href="#pauses" class="pauses">Pauses</a>
    <a href="#markering" class="marketing">Marketing</a>
    <a href="#sales" class="sales">Sales</a>
  </div>
  <div id="Agenda">
    <div class="row pauses"><b>Pause:</b> Break at 10:30</div>
    <div class="row marketing"><b>Marketing:</b> This is marketing</div>
    <div class="row sales"><b>Sales:</b> Sales is important</div>
  </div>
</div>