<html>
<head>
<title>无标题文档</title>
<script language="javascript" type="text/javascript">//js代码部分
function fun()
{
var b=document.getElementById("selterm").value;//获得选中选项的值
var new1,new2;
switch(b)
{
case "0":
{
document.getElementById("selcourse").length=0;
new1=new Option('java','java');
new2=new Option('C#','C#');
break;
}
case "1":
{
document.getElementById('selcourse').length=0;
new1=new Option("sql","sql");
new2=new Option('C','C');
break;
}
case "2":
{
document.getElementById('selcourse').length=0;
new1=new Option('linux','linux');
new2=new Option('uml','linux');
break;
}
document.getElementById('selcourse').options.add(new1);
document.getElementById('selcourse').options.add(new2);
}
}
</script>
</head>
<body>
<table width="382" border="1">
<tr>
<td width="372"><label>姓名:
<input type="text" name="textfield" />
</label></td>
</tr>
<tr>
<td>学期:
<label>
<select name="select"οnchange="fun()" id="selterm">
<option value="-1" >选择您的学期</option>
<option value="0" >第一学期</option>
<option value="1">第二学期</option>
<option value="2">第二学年</option>
</select>
</label></td>
</tr>
<tr>
<td> 课程 :
<label>
<select name="select2" id="selcourse">
<option value="-1">选择你的课程</option>
</select>
</label></td>
</tr>
</table>
</body>
</html>
2.利用数组也可以实现,并且方便,可以动态修改数组里面的值,由此实现
这个代码可以继续实现优化的
function fun()
{
var ay=new Array();//我这里一开始定义数组时将Array写错成array,o(︶︿︶)o 唉错好久才发现的
ay[0]=['java','java1','java2'];
ay[1]=['C1','C2','C3'];
ay[2]=['D1','D2','D3'];
var b=document.getElementById("selterm").value;
document.getElementById("selcourse").length=0;
switch(b)
{
case "0":
{
for(var i in ay[0])
{
document.getElementById('selcourse').options.add(new Option(ay[0][i],ay[0][i]));
}
break;
}
case "1":
{
for(var i in ay[1])
{
document.getElementById('selcourse').options.add(new Option(ay[1][i],ay[1][i]));
}
break;
}
case "2":
{
for(var i in ay[2])
{
document.getElementById('selcourse').options.add(new Option(ay[2][i],ay[2][i]));
}
break;
}
}
}
3.数组改进版
其实现方式:获取第一个下拉框的选中索引,其与数组的索引相差一,因此减一后可以实现数组索引和下拉框选中索引同步
然后再依次添加选中索引对应数组索引里面的值
function fun()
{
var ay=new Array();
ay[0]=['java','java1','java2'];
ay[1]=['C1','C2','C3'];
ay[2]=['D1','D2','D3'];
document.getElementById("selcourse").length=0;//清空自下拉框的所有项
var Index=document.getElementById("selterm").selectedIndex-1;
for(var i=0;i<ay[Index].length;i++)
{
document.getElementById('selcourse').options.add(new Option(ay[Index][i],ay[Index][i]));//new Option(ay[Index][i],ay[Index][i]))这个的作用是新建子选项
}
}