一、做一个省市级联列表
1.写的顺序:先写结构再写样式最后写逻辑
1)结构
<select>
<option>河北</option>
<option>河南</option>
<option>湖北</option>
</select>
<select>
<option>沧州</option>
<option>洛阳</option>
<option>武汉</option>
</select>
//select是下拉列表,option是下拉项
3)逻辑:1.定义一个放置省份的数组
<script>
var provice=["河北","河南","武汉"]
</script>
2.将省份数组拼接成option标签,放入第一个select标签中(接下来的步骤和代码直接写到下面的代码中)
<body>
<select id="sf"></select>
<select id="sl2"></select>
<script>
var provice =["河北","河南","湖北"]//定义一个放置省份的数组
//将省份数组拼接成option标签,放入第一个select标签中
var str=""
for(var n=0;n<provice.length;n++){
str=str+"<option>"+provice[n]+"</option>"
}
var sf=document.getElementById("sf")
//3.将拼接好的str字符串放入第一个select标签中
sf.innerHTML=str
//4.定义一个放置市的数组这需要用到二维数组。
//二维数组:var n=[[1,1,2],[23,52,11]]
var citys=[["沧州","石家庄"],["开封","洛阳"],["武汉","荆州"]]
//5.由于默认的第一个是河北,第二个框中默认的是河北省的市所以要小于city[0]的长度
var str2=""
for(var n=0;n<city[0].length;n++){
str2=str2+"<option>"+city[0][n]+"</option>"
}
//将拼接好的放入第二个select标签中
var sl2=document.getElementById("sl2")
sl2.innerHTML=str1
//当左侧select内容放生变化,右边的也随之发生变化
sl1.onchange=function(){
//找到数组变化的位置
var index=sl1.selectedIndex
//遍历数组
var str1=""
for(var n=0;n<citys[index].length;n++){
str1=str1+"<option>"+citys[index][n]+"</option>"
}
//第二个框的内容随之变化
sl2.innerHTML=str1
}
</script>
</body>