我有一个下拉列表和 5 个 div。我需要一次显示一个特定的 div 并隐藏另一个。这是我的方法 这是我的代码
<div data-role="content">
<div id="tab-1">
<br />
<div id="one" style="width: device-width; height: 150px;"></div>
<div id="two" style="width: device-width; height: 150px;"></div>
<div id="three" style="width: device-width; height: 150px;"></div>
<div id="four" style="width: device-width; height: 150px;"></div>
<div id="five" style="width: device-width; height: 150px;"></div>
<div class="ui-select">
<select name="usageDropDownList" id="usageDropDownList"
data-native-menu="false" tabindex="-1">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
</div</div>
这是我的 document.ready()
$(document).ready(function() {
$("#usageDropDownList").change(function() {
if ($(this).val() == 'one') {
$("#two").hide();
$("#three").hide();
$("#four").hide();
$("#five").hide();
$("#one").show();
} else if ($(this).val() == 'two') {
$("#one").hide();
$("#three").hide();
$("#four").hide();
$("#five").hide();
$("#two").show();
} else if ($(this).val() == 'three') {
$("#one").hide();
$("#two").hide();
$("#four").hide();
$("#five").hide();
$("#three").show();
} else if ($(this).val() == 'four') {
$("#one").hide();
$("#two").hide();
$("#three").hide();
$("#five").hide();
$("#four").show();
} else if ($(this).val() == 'five') {
$("#one").hide();
$("#two").hide();
$("#three").hide();
$("#four").hide();
$("#five").show();
}
});
});
有人可以建议我一种更好的方法吗?
最佳答案
这就是您所需要的:
$("#" + $(this).val()).show().siblings().hide();
分割:
$("#" + $(this).val()) // selects div with id equal to value of selected option
.show() // shows it
.siblings() // then selects all of the other divs next to it
.hide() // and hides them
更新:
因为还有<div class="ui-select">
在标记中的“数字”div 旁边,它也将被隐藏(这是不可取的)。您可以通过多种方式解决此问题,以下是两种:
1:只需在“数字”周围放置一个包装 div,即可使该 div 不再是同级:
<div> <!-- added this -->
<div id="one" style="width: device-width; height: 150px;"></div>
<div id="two" style="width: device-width; height: 150px;"></div>
<div id="three" style="width: device-width; height: 150px;"></div>
<div id="four" style="width: device-width; height: 150px;"></div>
<div id="five" style="width: device-width; height: 150px;"></div>
</div>
2:排除ui-select
具体来说:
$("#" + $(this).val()).show().siblings().not(".ui-select").hide();
关于javascript - 如何使用jquery有效隐藏其他同伴div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698629/