jQuery:选择菜单以显示和隐藏某些div元素 [英] Jquery: Select menu to show and hide certain div elements
问题描述
我正在寻找创建一个选择菜单,该菜单基于所选选项显示和隐藏某些div;像这样的东西:
I'm looking to create a select menu that shows and hide certain divs based on the selected option; something like this:
<select name="choose_colors" id="color_selector">
<option value="select_color">Select color</option>
<option value="red">Choose Red</option>
<option value="blue">Choose Blue</option>
<option value="green">Choose Green</option>
</select>
<div id="red_options" class="color_options">
...
</div>
<div id="blue_options" class="color_options">
...
</div>
<div id="green_options" class="color_options">
...
</div>
因此,如果使用者选择选择红色",则将显示#red_options的div,并且将隐藏#blue_options和#green_options.
So if the use selects "Choose Red", then the div for #red_options will show, and the #blue_options and #green_options will hide.
如果用户返回到默认选项选择颜色",则#red_options/#blue_options/#green div被隐藏.
If the user goes back to the default option "Select color", the #red_options/#blue_options/#green divs are hidden.
我该如何在Jquery中做到这一点?我以为会是这样:
How would I do that in Jquery? I thought it would be something like this:
<script>
$(".color_options").hide();
$('select[name="choose_colors"]').change(function () {
if ("Select color") {
$("#red_options").hide();
$("#blue_options").hide();
$("#green_options").hide();
}
if ("Red") {
$("#red_options").show();
}
if ("Blue") {
$("#blue_options").show();
}
if ("Green") {
$("#green_options").show();
}
});
</script>
当然不能正常工作.有什么想法吗?
Of course that's not working correctly. Any ideas?
推荐答案
尝试一下:
$("#color_selector").change(function() {
$(".color_options").hide();
$("#" + $(this).val() + "_options").show();
}
这可以利用下拉值中的匹配项以及div的命名方式,例如red
= red_options
This takes advantage of the matches in the drop down values and how you've named your divs, e.g. red
= red_options
这篇关于jQuery:选择菜单以显示和隐藏某些div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!