我有挑战根据从主类别中选择的内容选择子类别,当我从主类别中选择时,子类别仍然显示第二类别中的所有选项。 这是代码的片段
$(document).ready(function(){
$("#category").on("change",function(){
var selectedVal=$( "#category option:selected" ).val();
$("#subcategory > optgroup").attr("disabled","disabled");
$('#subcategory > optgroup[label="'+selectedVal+'"]').removeAttr("disabled");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category">
<option value="Fashion">Fashion</option>
<option value="Electronics">Electronics</option>
</select>
<select name="subcategory" id="subcategory">
<optgroup label="Fashion">
<option value="Men's wear">Men's wear</option>
<option value="Women's wear">Women's wear</option>
</optgroup>
<optgroup id="B" label="Electronics" disabled>
<option value="Television">Television</option>
<option value="Game Console">Game Console</option>
</optgroup>
</select>
&#13;
答案 0 :(得分:3)
将选择设置为您想要的选项。
load_only
&#13;
$(document).ready(function(){
var $optgroups = $('#subcategory > optgroup');
$("#category").on("change",function(){
var selectedVal = this.value;
$('#subcategory').html($optgroups.filter('[label="'+selectedVal+'"]'));
});
});
&#13;
答案 1 :(得分:1)
您可以使用解决方案
$(document).ready(function(){
$("#category").on("change",function(){
var selectedVal = $(this).find("option:selected" ).val();
$('#subcategory > optgroup[label="'+selectedVal+'"]')
.show()
.siblings("optgroup")
.css("display","none");
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="category">
<option value="Fashion">Fashion</option>
<option value="Electronics">Electronics</option>
</select>
<select name="subcategory" id="subcategory">
<optgroup label="Fashion">
<option value="Men's wear">Men's wear</option>
<option value="Women's wear">Women's wear</option>
</optgroup>
<optgroup id="B" label="Electronics">
<option value="Television">Television</option>
<option value="Game Console">Game Console</option>
</optgroup>
</select>
&#13;
希望这会对你有所帮助。