在学习省市联动示例的时候,首先在二维数组上栽了跟头,现将数组相关知识记录一下:
一维数组声明的两种方式:
第一种:
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
或者:
var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
第二种:
var mycars=new Array("Saab","Volvo","BMW")
二维数组声明的方式:
var cities = new Array(4);
cities[0] = new Array("东城区","西城区","宣武区","朝阳区");
cities[1] = new Array("黄浦区","徐汇区","长宁区","静安区");
cities[2] = new Array("济南市","青岛市","淄博市","枣庄市");
cities[3] = new Array("石家庄市","唐山市","秦皇岛市","邯郸市");
最后有一个疑问,思考了很久也没有获得答案:
示例中必须遍历省份,然后与所传值进行比较,相同的话再进行城市的遍历,即需要双重遍历,我发现不需要遍历省份也可以完成
示例代码:
<script>
//1.创建一个二维数组用于存储省份和城市
var cities = new Array(3);
cities[0] = new Array("武汉市","黄冈市","襄阳市","荆州市");
cities[1] = new Array("长沙市","郴州市","株洲市","岳阳市");
cities[2] = new Array("石家庄市","邯郸市","廊坊市","保定市");
cities[3] = new Array("郑州市","洛阳市","开封市","安阳市");
function changeCity(val){
//7.获取第二个下拉列表
var cityEle = document.getElementById("city");
//9.清空第二个下拉列表的option内容
cityEle.options.length=0;
//2.遍历二维数组中的省份
for(var i=0;i<cities.length;i++){
//注意,比较的是角标
if(val==i){
//3.遍历用户选择的省份下的城市
for(var j=0;j<cities[i].length;j++){
//alert(cities[i][j]);
//4.创建城市的文本节点
var textNode = document.createTextNode(cities[i][j]);
//5.创建option元素节点
var opEle = document.createElement("option");
//6.将城市的文本节点添加到option元素节点
opEle.appendChild(textNode);
//8.将option元素节点添加到第二个下拉列表中去
cityEle.appendChild(opEle);
}
}
}
}
</script>
我自己的代码:
<script type="text/javascript">
function selectCity(index){
var cities = new Array(4);
cities[0] = new Array("东城区","西城区","宣武区","朝阳区");
cities[1] = new Array("黄浦区","徐汇区","长宁区","静安区");
cities[2] = new Array("济南市","青岛市","淄博市","枣庄市");
cities[3] = new Array("石家庄市","唐山市","秦皇岛市","邯郸市");
var cityEle = document.getElementById("cityid");
cityEle.options.length = 0;
for (var i = 0;i < cities[index].length;i++) {
var optionNode = document.createElement("option");
var textNode = document.createTextNode(cities[index][i]);
optionNode.appendChild(textNode);
cityEle.appendChild(optionNode);
}
}
</script>
以后学明白了再来看看怎么回事吧