分析:
1. 首先定义window.onload来初始化级联菜单的初始值(一级菜单有值,其他的均为"请选择").
2. 定义一级菜单的onchange事件函数fun1,传递一级菜单的selectedIndex.通过selectedIndex获取二级菜单的options
3. 定义二级菜单的onchange事件函数fun2,传递二级菜单的selectedIndex,并获取一级菜单的selectedIndex,获取三级菜单中options的值.
4. 注意一级菜单变化与二级菜单变化的联动,即在fun1中默认选择option的selectedIndex同时关联fun2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三级级联菜单</title>
<style>
#one,#two,#three{
width: 300px;
height: 35px;
}
</style>
</head>
<body>
<form>
<select id="one" onchange="fun1(this.selectedIndex)"></select>
<select id="two" onchange="fun2(this.selectedIndex)"></select>
<select id="three"></select>
</form>
</body>
<script>
//定义三个数组(静态的)
var first = ["--请选择--","1","2","3"];
var second = [["--请选择--"],["11","12","13"],["21","22","23"],["31","32","33"]];
var third = [[["--请选择--"]],[["111","112","113"],["121","122","123"],["131","132","133"]],
[["211","212","213"],["221","222","223"],["231","232","233"]],[["311","312","313"],
["321","322","323"], ["331","332","333"]]];
//获取三个select的dom对象
var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
//定义window.onload的事件初始化页面
window.onload = function() {
//初始化一级菜单的数组
one.options.length = first.length;
for (var i = 0; i < first.length; i++) {
//option的文本
one.options[i].text = first[i];
//option代表的表单值
one.options[i].value = first[i];
}
//初始化二级菜单
two.options.length = 1;
two.options[0].text = second[0][0];
two.options[0].value = second[0][0];
//初始化三级菜单
three.options.length = 1;
three.options[0].text = third[0][0][0];
three.options[0].value = third[0][0][0];
};
//定义一级菜单发生改变时候二级菜单列表改变
function fun1(index) {
two.options.length = second[index].length;
for (var i = 0; i < two.options.length; i++) {
two.options[i].text = second[index][i];
two.options[i].value = second[index][i];
//默认选择第一列
two.selectedIndex = 0;
//关联fun2,实现二级change的同时三级也change
fun2(0);
}
}
//定义二级菜单发生改变时候三级菜单列表改变
function fun2(index1) {
var index = one.selectedIndex;
three.options.length = third[index][index1].length;
for (var i = 0; i < three.options.length; i++) {
three.options[i].text = third[index][index1][i];
three.options[i].value = third[index][index1][i];
three.selectedIndex = 0;
}
}
</script>
</html>