javascript制作二级联动菜单
二级联动菜单的制作中我主要应用了:
*数组API的arr.join("分隔符")的方法
*select的change事件
*html标签元素<option></option>通过字符串拼接动态生成
*数组中的元素为数组
制作二级联动菜单的具体代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<select name="city" id="city1"></select>
<select name="vilage" id="vilage"></select>
<script>
(function(){
var arr=["江苏","浙江"];
var arr1 = [["宿迁","苏州","扬州","南京"],["杭州","绍兴","传播"]];
var arr2 = ["杭州","绍兴","传播"];
var html = "";
for(var i=1;i<arr.length+1;i++){
html += "<option value='"+i+"'>"+arr[i-1]+"</option>";
}
document.getElementById("city1").innerHTML=html;
//默认arr1
var html2 = "<option>";
html2 += arr1[0].join("</option><option>");
html2 +="</option>";
document.getElementById("vilage").innerHTML=html2;
document.getElementById("city1").addEventListener("change",function(){
//获取value值
var val = this.value;
//alert(val);
var html3 ="<option>";
html3 += arr1[val-1].join("</option><option>");
html3 += "</option>";
document.getElementById("vilage").innerHTML=html3;
});
})();
</script>
</body>
</html>
页面效果如下图所示:
//选择江苏省时显示相应城市:
//选择浙江省时显示相应城市:
![](https://images2018.cnblogs.com/blog/1331873/201802/1331873-20180225133246692-182172725.png)
以上代码为本人原创,如有更好的想法或有错误,请指教!!!!