我有一个下拉选择,一旦选择,它将显示值和类共享相同名称的 div,并隐藏所有其他内容。
我怎样才能让它在您选择之前显示全部并且仅在您选择选项后隐藏?
编辑 我已经更新了要运行的代码片段,并且内置了标记,但是在我本地的 php 上。
修改后的问题
当未选择任何内容且选择为默认设置时,如何调整 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>
关于javascript - 如何设置一个简单的 jQuery 隐藏/显示函数以在隐藏之前显示所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72017279/