如果类与第一个选择列表中选择的选项的类不同,我使用jQuery not()
方法隐藏第二个选择列表中的选项元素。
这是我的jQuery代码,它在FF中运行,但不适用于Chrome或Safari(尚未检查IE)。我对此有些新意,所以可能有一个简单的修复方法或更容易实现的方法。感谢。
$('#formcategory').on('change', function() {
var selected = $('#formcategory :selected').attr("class");
$('#formsubcategory').find('option').not("."+selected).hide();
});
<select id="formcategory" name="Category">
<option value="Select One">Select One</option>
<option class="BloodSample" value="1">Blood Sample</option>
<option class="Exercise" value="2">Exercise</option>
<option class="InsulinInjection" value="3">Insulin Injection</option>
<option class="Meal" value="4">Meal</option>
<option class="Symptoms" value="5">Symptoms</option>
<option class="UrineSample" value="6">Urine Sample</option>
</select>
<label id="lblsubcategory" for="formsubcategory" style="display: inline;">Subcategory</label>
<select id="formsubcategory" name="Subcategory" style="display: block;">
<option selected="selected" value="Select One" style="display: none;">Select One</option>
<option class="Symptoms" value="51">Lethargy</option>
<option class="Symptoms" value="52">Vomiting</option>
<option class="Symptoms" value="53">Diarrhea</option>
<option class="Symptoms" value="54">Seizures</option>
<option class="Symptoms" value="55">Missed Meal</option>
<option class="Symptoms" value="56">Poor Appetite</option>
<option class="Symptoms" value="57">Excessive Drinking</option>
<option class="Symptoms" value="58">Excessive Urination</option>
<option class="UrineSample" value="61" style="display: none;">Positive - Glucose</option>
<option class="UrineSample" value="62" style="display: none;">Negative - Glucose</option>
<option class="UrineSample" value="63" style="display: none;">Positive - Ketones</option>
<option class="UrineSample" value="64" style="display: none;">Negative -Ketones</option>
</select>
答案 0 :(得分:2)
你永远不会显示元素,只是隐藏它们:
$('#formcategory').on('change', function() {
var selected = $('#formcategory :selected').prop("class");
if (selected.length) $('#formsubcategory option').show().not('.'+selected).hide();
});
修改强>
添加了一个空className的检查,以避免在重新选择第一个选项时出错!