我做错了什么?当我选择一个特定选项时是否有解决方案,它只打开该特定字段而不是同时打开?我唯一的解决方案是添加DRY 代码
HTML
<select type="type-switcher" name="type-switcher" id="js_type_switcher" class="product-type-switcher">
<option value="type-switcher">Type Switcher</option>
<option value="discs">discs</option>
<option value="books">books</option>
<option value="furnitures">furnitures</option>
</select>
当我选择所需的选择选项时,我有一些需要显示的字段
<div name="size" class="form-field hide-form-field">
<div class="form-field">
<span>Size:</span>
<input type="text" name="size">
</div>
<div name="weight" class="form-field hide-form-field">
<div class="form-field">
<span>Weight:</span>
<input type="text" name="weight">
</div>
<div name="dimensions" class="form-field hide-form-field">
<div class="form-field">
<span>Height:</span>
<input type="text" name="dimensions-height">
</div>
CSS 默认字段是隐藏的
.show-form-field {
display: unset;
}
jQuery 问题是,当我执行一个切换案例(例如“discs”)而不是只打开一个磁盘属性字段时,它会打开所有字段!我能想到的唯一解决方案是在每个函数中隐藏另外两个字段,但代码变得非常DRY。当我选择案例“光盘”时,是否有更好的解决方案它只打开大小字段而另外两个保持隐藏。
$('.product-type-switcher').on('change', function(){
let showDiscsSize = $('div[name="size"]').addClass("show-form-field");
let showBooksWeight = $('div[name="weight"]').addClass("show-form-field");
let showFurnituresDimensions = $('div[name="dimensions"]').addClass("show-form-field");
function showDiscAttribute() {
showDiscsSize;
//showBooksWeight.removeClass("show-form-field");
//showFurnituresDimensions.removeClass("show-form-field");
}
function showBooksAttribute() {
showBooksWeight;
//showDiscsSize.removeClass("show-form-field");
//showFurnituresDimensions.removeClass("show-form-field");
}
function showDimensionAttribute() {
showFurnituresDimensions;
//showDiscsSize.removeClass("show-form-field");
//showBooksWeight.removeClass("show-form-field");
}
switch($(".product-type-switcher option:selected").val()) {
case 'type-switcher':
$(".hide-form-field").removeClass("show-form-field");
break;
case 'discs':
showDiscAttribute();
break;
case 'books':
showBooksAttribute();
break;
case 'furnitures':
showDimensionAttribute();
break;
default:
}
});
ps 我完全是程序员的初学者!