我有一個下拉選擇,一旦選擇,它將顯示值和類共享相同名稱的 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>
uj5u.com熱心網友回復:
您可以進行一些更改:
使用
$(this).val()(this=select)value=從 select 選項中獲取,無需像這樣為您查找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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464801.html
