javascript - 下拉选择jQuery
问题描述
我正在制作一个下拉列表,并希望在选择 id="residential" 时显示 div class="residential-options",并在选择 id="commercial" 时显示 div class="commercial-options"。
这是我的 HTML:
<div class= "row">
<select id='building-type'>
<option disabled selected value> -- select an option -- </option>
<option id="residential" value="residential" [...]>Residential</option>
<option id="commercial" value="commercial " [...]>Commercial</option>
<option id="corporate" value="corporate" [...]>Corporate</option>
<option id="hybrid" value="hybrid" [...]>Hybrid</option>
</select>
</div>
<div class="residential-options">
<div id="number-of-apartments" >
<label>N. of Apartments *</label>
<input [...]>
</div>
<div id="number-of-basements" >
<label>N. of Basements *</label>
<input [...]>
</div>
</div>
<div class="commercial-options">
<div id="number-of-floors" >
<label>N. of Floors *</label>
<input [...]>
</div>
这是我的 jQuery:
$("#building-type").change(function() {
($('#residential').is(':checked'))
$('.residential-options').show();
$('.commercial-options').hide();
$('.corporate-options').hide();
$('.hybrid-options').hide()
});
$("#building-type").trigger("change");
$("#building-type").change(function() {
($('#commercial').is(':checked'))
$('.commercial-options').show();
$('.residential-options').hide();
$('.corporate-options').hide();
$('.hybrid-options').hide()
});
$("#building-type").trigger("change");
它只显示我点击的 div class="commercial-options" 。谢谢你的帮助!
解决方案
您的代码可以大大简化,包括删除.trigger()
调用。
$("#building-type").change(function() {
$('div[class*="options"]').hide(); // hide all '*-option' divs
// Determine which option was selected and display the corresponding div:
['residential', 'commercial', 'corporate', 'hybrid'].forEach(function(base){
if ($('#' + base + ':checked').length) {
$(`.${base}-options`).show();
}
})
})
推荐阅读
- anaconda - 防止anaconda在没有激活virtual-env时添加`(base)`进行提示(即virtual-env = anaconda base)
- asp.net - 在 Timer 刻度处显示(标签控件)内部(中继器控件)
- python - 使用 OpenCV 改进图像中的矩形轮廓检测
- javascript - 使用多个渲染共享深度缓冲区?
- docker - 如何从公共网络(互联网)访问 docker 服务?
- python - 如何获取当前的 GPIO?
- c++ - 如何减少应用程序的堆栈和堆大小?
- angular - 为什么过滤器运算符的参数没有采用可观察数组中存在的属性
- api - 我在 nativescript-vue 中使用 fetch 时遇到问题
- heroku - 在 Web 上部署前端和后端代码