Javascript实现多级联动下拉框Demo代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JS多级联动下拉框Demo</title> <script type="text/javascript" language="javascript"> function class_liandong(array) { this.array = array; this.indexName = ''; this.obj = ''; // 参数:当前onchange的select ID,要设置的select ID this.subSelectChange = function (selectName1, selectName2) { var obj1 = document.all[selectName1]; var obj2 = document.all[selectName2]; var objName = this.toString(); var me = this; obj1.onchange = function () { me.optionChange(this.options[this.selectedIndex].value, obj2.id) } } //设置第一个select // 参数:indexName指选中项,selectName指select的ID this.firstSelectChange = function (indexName, selectName) { this.obj = document.all[selectName]; this.indexName = indexName; this.optionChange(this.indexName, this.obj.id) } // indexName指选中项,selectName指select的ID this.optionChange = function (indexName, selectName) { var obj1 = document.all[selectName]; var me = this; obj1.length = 0; obj1.options[0] = new Option("请选择", ''); for (var i = 0; i < this.array.length; i++) { if (this.array[i][1] == indexName) { obj1.options[obj1.length] = new Option(this.array[i][2], this.array[i][0]); } } } } </script> </head> <body> <form name="form1" action="" method="post"> <select id="s1" name="s1"> <option selected="selected"></option> </select> <select id="s2" name="s2"> <option selected="selected"></option> </select> <select id="s3" name="s3"> <option selected="selected"></option> </select> </form> </body> <script type="text/javascript"> var array = new Array(); array[0] = new Array("11", "根目录", "一级部门1"); //数据格式 ID,父级ID,名称 array[1] = new Array("12", "根目录", "一级部门2"); array[2] = new Array("21", "11", "二级部门1"); array[3] = new Array("22", "11", "二级部门2"); array[4] = new Array("23", "12", "二级部门3"); array[5] = new Array("24", "12", "二级部门4"); array[6] = new Array("31", "21", "三级部门1"); array[7] = new Array("32", "22", "三级部门2"); array[8] = new Array("33", "22", "三级部门3"); array[9] = new Array("34", "23", "三级部门4"); array[10] = new Array("35", "24", "三级部门5"); var liandong = new class_liandong(array); //设置数据源 liandong.firstSelectChange("根目录", "s1"); //设置第一个选择框 liandong.subSelectChange("s1", "s2"); //设置子级选择框 liandong.subSelectChange("s2", "s3"); </script> </html>