如何设置一个简单的 jQuery hide/show 函数在隐藏之前显示所有内容?

How to set a simple jQuery hide/show function to show all before hide?

我有一个下拉 selection,一旦它 select 它将显示 div 其中值和 class 共享相同的名称并隐藏所有其他内容.

我怎么能在你之前select它会显示所有内容并且只在你select一个选项之后隐藏?

编辑 我已将代码片段更新为 运行,但在我的本地已内置标记 php.

修改问题

当 none 被 selected 且 selection 处于默认状态时,我如何调整 jQuery 以显示所有内容。

var $j = jQuery.noConflict();
        $j(document).ready(function () {
            $j("select").change(function () {
                $j(this).find("option:selected").each(function () {
                    var optionValue = $j(this).attr("value");
                    if (optionValue) {
                        $j(".career_div").not("." + optionValue).hide();
                        $j("." + optionValue).show();
                    } else {
                        $j(".career_div").hide();
                    }
                });
            })
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="all">Default</option>
    <option value="one">Intelligence (2)</option>
  <option value="two">Engineering (2)</option>
  <option value="three">Marketing (0)</option>
</select>

<section class="py-3 section-grey">
  <div class="container">
    <div class="row">
      <div class="col-12 one career_div">
        <strong>Intelligence</strong>
      </div>
      <div class="col-12 one career_div">
        <strong>Intelligence</strong>
      </div>
      <div class="col-12 two career_div">
        <strong>Engineering</strong>
      </div>
      <div class="col-12 line-grey two career_div">
        <strong>Engineering</strong>
      </div>
    </div>
  </div>
</section>

您可以进行一些更改:

  • 使用$(this).val()(this=select)从select选项中得到value=,不需要再找option:selected 并循环为 .val() 为您执行此操作。

  • 检查“全部”然后不应用过滤器

  • 正如评论中所指出的,“一”/“二”绕错了方向(对功能没有影响,只是让它看起来像是错误的)

更新的代码段:

$(document).ready(function($) {
  $("select").change(function() {
    var opt = $(this).val();
    if (opt === "all") {
      $(".career_div").show();
    } else {
      $(".career_div").hide();
      $("." + opt).show();
    }   
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="all">Default</option>
  <option value="two">Engineering (2)</option>
  <option value="one">Intelligence (2)</option>
  <option value="three">Marketing (0)</option>
</select>

<section class="py-3 section-grey">
  <div class="container">
    <div class="row">
      <div class="col-12 one career_div">
        <strong>Intelligence</strong>
      </div>
      <div class="col-12 one career_div">
        <strong>Intelligence</strong>
      </div>
      <div class="col-12 two career_div">
        <strong>Engineering</strong>
      </div>
      <div class="col-12 line-grey two career_div">
        <strong>Engineering</strong>
      </div>
    </div>
  </div>
</section>