基于选择选项 jquery 显示/隐藏 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2975521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
show/hide div based on select option jquery
提问by yogsma
Here is my code. Why it doesn't work?
这是我的代码。为什么它不起作用?
<Script>
$('#colorselector').change(function() {
$('.colors').hide();
$('#' + $(this).val()).show();
});
</Script>
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
</Select>
<div id="red" class="colors" style="display:none"> .... </div>
<div id="yellow" class="colors" style="display:none"> ... </div>
<div id="blue" class="colors" style="display:none"> ... </div>
回答by user113716
You're running the code before the DOM is loaded.
您正在加载 DOM 之前运行代码。
Try this:
尝试这个:
Live example:
现场示例:
$(function() { // Makes sure the code contained doesn't run until
// all the DOM elements have loaded
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
回答by saurabh yadav
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value
对每个值都这样做
回答by Colonel Sponsz
You are missing a :selected
on the selector for show()
- see the jQuery documentationfor an example of how to use this.
您:selected
在选择器上缺少 a show()
-有关如何使用它的示例,请参阅jQuery 文档。
In your case it will probably look something like this:
在您的情况下,它可能看起来像这样:
$('#'+$('#colorselector option:selected').val()).show();
回答by Summved Jain
To show the div while selecting one value and hide while selecting another value from dropdown box: -
要在选择一个值时显示 div 并在从下拉框中选择另一个值时隐藏:-
$('#yourselectorid').bind('change', function(event) {
var i= $('#yourselectorid').val();
if(i=="sometext") // equal to a selection option
{
$('#divid').show();
}
elseif(i=="othertext")
{
$('#divid').hide(); // hide the first one
$('#divid2').show(); // show the other one
}
});