<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
var country=[
{provice:"北京",city:["朝阳","海淀","西城"]},
{provice:"黑龙江",city:["哈尔滨","绥化","大庆","牡丹江"]},
{provice:"辽宁",city:["沈阳","鞍山"]}
];
for(var i = 0 ; i < country.length ; i++){
var obj = $("<option value='"+i+"'>"+country[i].provice+"</option>");
$("#pro").append(obj);
}
$("#pro").change(function(){
//清空市级的子节点
$("#city").empty();
var value = $("#pro").val();
//将String的value转换成int
value = parseInt(value);
//alert(typeof(value)); 这句话可以输出一个var的类型
var city = country[value].city;
for( var i = 0 ; i < city.length ; i++){
var opt = $("<option>"+city[i]+"</option>")
$("#city").append(opt);
}
})
});
</script>
</head>
<body>
<select id="pro">
<option>--省份--</option>
</select>
<select id="city">
<option>--城市--</option>
</select>
</body>
</html>
第一种容易添加和扩展
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
var a=[["北京","海淀"],["哈尔滨","牡丹江","大庆"],["沈阳"]]
$("#s1").change(function(){
var s = $("#s1").val();
//alert(a[s]);
var obj = eval(s);
var b = a[obj];
$("#s2").empty();
for(var i=0;i<b.length;i++){
$("#s2").append("<option>"+b[i]+"</option>");
}
})
})
</script>
</head>
<body>
<select id="s1">
<option value="-1">--请选择--</option>
<option value="0">北京</option>
<option value="1">黑龙江</option>
<option value="2">辽宁</option>
</select>
<select id="s2">
</select>
</body>
</html>