js 实现二级联动
程序员文章站
2022-11-22 07:55:16
onchange 事件 使用字典方式添加数据 一级数据显示 二级数据联动 方式一 二级数据联动 方式二 ......
onchange 事件
<body> <select id="province" onchange="func1()"> <option value="shandong">山东</option> <option value="hebei">河北</option> <option value="beijing">北京</option> </select> </body> <script> function func1(){ var pro = document.getelementbyid("province"); console.log(pro.value) } </script>
使用字典方式添加数据
一级数据显示
<body> <select id="province" > </select> </body> <script> data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]}; var pro = document.getelementbyid("province"); for (var i in data){ var option_pro = document.createelement("option"); option_pro.innerhtml=i; pro.appendchild(option_pro); } </script>
二级数据联动 方式一
<body> <select id="province" onchange="func1(this)" > </select> <select id="city"></select> </body> <script> data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]}; var pro = document.getelementbyid("province"); var city = document.getelementbyid("city"); for (var i in data){ var option_pro = document.createelement("option"); option_pro.innerhtml=i; pro.appendchild(option_pro); } function func1(self){ //console.log((self.options[self.selectedindex]).innerhtml); var choice = (self.options[self.selectedindex]).innerhtml; var options = city.children; for (var k=0; k<options.length; k++){ city.removechild(options[k--]); } for (var i in data[choice]){ var option_city = document.createelement("option"); option_city.innerhtml = data[choice][i]; city.appendchild(option_city); } } </script>
二级数据联动 方式二
<body> <select id="province" onchange="func1(this)" > </select> <select id="city"></select> </body> <script> data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]}; var pro = document.getelementbyid("province"); var city = document.getelementbyid("city"); for (var i in data){ var option_pro = document.createelement("option"); option_pro.innerhtml=i; pro.appendchild(option_pro); } function func1(self){ //console.log((self.options[self.selectedindex]).innerhtml); var choice = (self.options[self.selectedindex]).innerhtml; city.options.length=0; for (var i in data[choice]){ var option_city = document.createelement("option"); option_city.innerhtml = data[choice][i]; city.appendchild(option_city); } } </script>