2009-06-25 145 views
5

我的代码:如何显示/隐藏的div(jQuery的)

<select id="select"> 
<option id="1" value="thai language">option one</option> 
<option id="2" value="eng language">option two</option> 
<option id="3" value="other language">option three</option> 
</select> 

<div id="form1">content here</div> 
<div id="form2">content here</div> 
<div id="form3">content here</div> 

我想是显示DIV#form1的时候选择选项1,隐藏窗口2 + form3,或 选择选项2显示div#form2并隐藏form1 + form2

回答

15
$('#select').change(function() { 
    $('#form1, #form2, #form3').hide(); 
    $('#form' + $(this).find('option:selected').attr('id')).show(); 
}); 

请注意,ID不应该以数字开头,但上面应该这样做。

+1

沿着我在想什么线。 $(this).attr('id')不会引用select本身的id?我想我必须得到选择索引,抓住这个选项,然后得到ID。 – Sampson 2009-06-25 11:00:11

0

像这样的东西?

var optionValue = $("#select").val(); 

$('#form1, #form2, #form3').hide(); 

switch(optionValue) 
{ 
case 1: 
    $("#form1").show(); 
    break; 
case 2: 
    $("#form2").show(); 
    break; 
case: 3: 
    $("#form3").show(); 
    break; 
} 
0

只隐藏以前显示的div不是更好吗? 所以;

var selection = 0; 
$('#select').change(function() { 
    $('#form' + selection).hide(); 
    selection = $(this).val(); 
    $('#form' + selection).show(); 
}); 

请注意,ID不应以数字开头,但上面应该这样做。

2

如果您的形式是大的,你可以把他们在这样单独的文件,

$(document).ready(function() { 
    $('#select').change(function() { 
     $("#myform").load(this.value); 
    }); 
}); 


<select id="select"> 
<option value="blank.htm">Select A Form</option> 
<option value="test1.htm">option one</option> 
<option value="test2.htm">option two</option> 
<option value="test3.htm">option three</option> 
</select> 

<div id="myform" ></div> 
0

更好的版本:

$('#select').change(function() { 
    $('div').not('#form' + $(this).find('option:selected').attr('id')).hide(); 
    $('#form' + $(this).find('option:selected').attr('id')).show(); 
});