...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body onload="allTerm()">
<form id="form1" name="form1">
<table width="300" border="1" align="center">
<tr>
<td width="70" align="center">学期</td>
<td>
<select id="sTerm" onchange="cTerm()">
<option>请选择学期</option>
</select>
</td>
</tr>
<tr>
<td align="center">课程</td>
<td>
<select id="sCourse">
<option>请选择学期所对应的课程</option>
</select>
</td>
</tr>
</table>
</form>
<script src="js/select.js"></script>
</body>
</html>
...
select.js
//声明一个二维数组
//语法:1.var array[0]=[]
// 2. var array=[[1,2],[3,4]]
var cList = new Array(); cList["第一学期"] = ["java", "nodejs", "angularjs", "webpack"]; cList["第二学期"] = ["gulp", "C#", "SQL", "function"]; cList["第三学期"] = ["CSS", "HTML", "HTMLS", "JavaScript"];
//正在页面首次加载的时候要调用函数
-
//1.根据Id选取select节点 sTerm:HTML DOM select对象function allTerm() {
-
//2.add() 方法用于向 <select> 添加一个 <option> 元素。var sTerm = document.getElementById("sTerm");
// 语法:sTerm.add(new Option(),null) for (var i in cList) { sTerm.add(new Option(i), null); } }
//将每个学期所对应的课程添加到第二个下拉列表
-
function cTerm() {
//获取到sTerm元素的值
-
var sTerm = document.getElementById("sTerm").value;
//获到sCourse节点元素
-
var sCourse = document.getElementById("sCourse");
//将sCourse中option的默认值清除
-
sCourse.options.length = 0;
//要将学期所对应的课程添加到sCourse下拉列表中
for (var i in cList) { //i的值为第一学期,第二学期,第三学期 //如果原数组中的学期与第一个下拉列表中选取的学期一致 if (i == sTerm) { for (var j in cList[i]) { sCourse.add(new Option(cList[i][j]), null); } } } }