jQuery toggleclass 2 div - 打开一个并关闭另一个

jQuery toggleclass 2 divs - open one & close the other

我有 2 个 div 使用 toggleClass 打开,如下所示:

<!-- links to open div's -->
<div class="sort-filter">
  <div class="sort">
    <a href="#" class="sort"><em class="fa fa-sort"></em> SORT</a>
  </div>
  <div class="filter">
    <a href="#" class="filter"><em class="fa fa-filter"></em> FILTER</a>
  </div>
</div>

<!-- divs to toggle open/close -->
<div class="search-options clearfix" style="display: none;">
  content options here
</div>
<div class="search-filters clearfix" style="display: none;">
  content filters here
</div>

我使用以下 jQuery 来切换 div:

<script type="text/javascript">
$(function ($) {
    var search_options = $('.search-options');
    $('a.sort').click(function () {
        $(this).toggleClass('show');
        search_options.slideToggle(400);
        if ( !$(this).hasClass('show') ) {
            $('a.filter').removeClass('show'); // hide the other one
        }
        return false;
    });
    var search_filters = $('.search-filters');
    $('a.filter').click(function () {
        $(this).toggleClass('show');
        search_filters.slideToggle(400);
        if ( !$(this).hasClass('show') ) {
            $('a.sort').removeClass('show'); // hide the other one
        }
        return false;   
     });
});
</script>

但是我的逻辑很糟糕。

我希望一个 link 关闭另一个 div 如果打开,反之亦然。

有什么想法吗?

jsfiddle here...

您当前的代码从切换按钮中删除了显示标志,但实际上并没有执行任何隐藏内容区域的操作。您可以添加一个 slideUp() 来执行此操作:

$(function ($) {
    var search_options = $('.search-options');
    $('a.sort').click(function () {
        $(this).toggleClass('show');
        search_options.slideToggle(400);
        if ( $(this).hasClass('show') ) {
            $('a.filter').removeClass('show'); // mark the other as hidden
            search_filters.slideUp(400); // hide the other one
        }
        return false;
    });
    var search_filters = $('.search-filters');
    $('a.filter').click(function () {
        $(this).toggleClass('show');
        search_filters.slideToggle(400);
        if ( $(this).hasClass('show') ) {
            $('a.sort').removeClass('show'); // mark the other as hidden
            search_options.slideUp(400); // hide the other one
        }
        return false;   
     });
});

这里是 fiddle:http://jsfiddle.net/yj9f5qh8/