JavaScript二级联动
就是两个下拉列表框,我假设它有两个下拉列表(其实还可以有更多),第一个下拉列表中让你选择的省,而另一个下拉列表让你选择的是城市,当你在省的下拉列表中的选择发生改变的时候,城市的下拉列表也应当跟着你所选择的省名称而发生改变,这样就产生了一种联动的较果也就是简单的二级联动。
具体看代码
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title></title> | |
| </head> | |
| <body> | |
| <select id="country"> | |
| <option value="">国家</option> | |
| </select> | |
| <select id="city"> | |
| <option value="">城市</option> | |
| </select> | |
| <script type="text/javascript"> | |
| var country = [ | |
| ["中国", "北京","上海","重庆"], | |
| ["美国","华盛顿","纽约","拉斯维加斯"], | |
| ["日本","东京","横滨","神户"] | |
| ] | |
| //获取到两个下拉列表 | |
| var country1 = document.getElementById("country"); | |
| var city1 = document.getElementById("city"); | |
| //把国家名装到第一个下来框里面 | |
| function countryTosel(){ | |
| for(var i=0;i<country.length;i++){ | |
| //动态创建option标签 | |
| var option1 = document.createElement("option"); | |
| option1.innerHTML = country[i][0];//把国家名装到option里面 | |
| country1.appendChild(option1);//把option放到第一个下拉列表里面 | |
| } | |
| } | |
| countryTosel(); | |
| //把城市名放到第二个下拉列表里面 | |
| function cityToSel(index){ | |
| for(var j=1;j<country[index].length;j++){ | |
| var option2 = document.createElement("option"); | |
| option2.innerHTML = country[index][j];//把城市名装到option里面 | |
| city1.appendChild(option2);//把option放到第二个下拉列表里面 | |
| } | |
| } | |
| //cityToSel(1); | |
| country1.onchange = function(){ | |
| //selectedIndex,下拉列表的option对应的位置 | |
| //alert(this.selectedIndex); | |
| city1.innerHTML = "<option value=''>城市</option>"; | |
| if(this.selectedIndex!=0){ | |
| cityToSel(this.selectedIndex-1) | |
| } | |
| } | |
| </script> | |
| </body> | |
| </html> | |

浙公网安备 33010602011771号