jquery - jQuery select:option 为什么当我选择选项一来显示特定字段但它打开所有字段时?
问题描述
我做错了什么?当我选择一个特定选项时是否有解决方案,它只打开该特定字段而不是同时打开?我唯一的解决方案是添加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 我完全是程序员的初学者!
解决方案
我必须先提出一些建议。
- 缺少三个 div 结束标签。必须先解决这个问题。
以下标签缺少 div 结束标签。
<div name="size" class="form-field hide-form-field">
<div name="weight" class="form-field hide-form-field">
<div name="dimensions" class="form-field hide-form-field">
在用户选择任何选项之前,应隐藏输入字段
.hide-form-field{ 显示:无;}
.product-type-switcher on change 事件应包含在
jQuery("文档").ready(函数(){
});
不确定“让 showDiscsSize”、“让 showBooksWeight”、“让 showFurnituresDimensions”这些代码。我移动了“.addClass("show-form-field");” 直接到相关函数。
每次首先选择选项时,我们都必须删除当前可用的“show-form-field”。我在 on change 函数中添加了这个。这将重置先前显示的输入,并且只显示与当前选择的输入选项相关的输入字段。