<!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>
</head>
<body οnlοad="tm_init_pronince()">
<select id="province" οnchange="tm_city_change(this)"></select>
<select id="city" οnchange="tm_areas_change(this)"></select>
<select id="area"></select>
<script type="text/javascript">
function tm_init_pronince(){
var selectDom = document.getElementById("province");
var arr = [{"id":1001,"name":"湖南省"},{"id":1002,"name":"湖北省"}];
/*var html = "<option value=''>--请选择--</option>";
for(var i=0;i<arr.length;i++){
html += "<option value='"+arr[i].id+"'>"+arr[i].name+"</option>";
}
selectDom.innerHTML = html; */
var optionEmpty = document.createElement("option");
optionEmpty.value = "";
optionEmpty.text = "请选择";
selectDom.appendChild(optionEmpty);
for(var i=0;i<arr.length;i++){
var option = document.createElement("option");
option.value = arr[i].id;
option.text = arr[i].name;
selectDom.appendChild(option);
}
};
//城市数据
var cityDatas = {
"1001":"100101#长沙,100102#郴州,100103#株洲",
"1002":"100201#武汉,100202#太远,10023#十堰"
};
var areasDatas = {
"100101" :"10010101#雨花区,10010102#芙蓉区",
"100102" :"10010201#桂阳县,10010202#永兴区",
"100201" :"10020101#汉口,10020102#汉阳,10020103#武昌"
};
//1:了解数据层级接口
//2:javascript元素创建,定义和追加
function tm_city_change(obj){
var value = obj.value;
var datas = cityDatas[value];
var cityDom = document.getElementById("city");
cityDom.innerHTML = "";
var optionEmpty = document.createElement("option");
optionEmpty.value = "";
optionEmpty.text = "请选择";
cityDom.appendChild(optionEmpty);
if(datas){
var citys = datas.split(",");
for(var i=0;i<citys.length;i++){
var option = document.createElement("option");
var v = citys[i].split("#");
option.value = v[0];
option.text = v[1];
cityDom.appendChild(option);
}
}
};
function tm_areas_change(obj){
var value = obj.value;
var datas = areasDatas[value];
var areaDom = document.getElementById("area");
areaDom.innerHTML = "";
var optionEmpty = document.createElement("option");
optionEmpty.value = "";
optionEmpty.text = "请选择";
areaDom.appendChild(optionEmpty);
if(datas){
var areas =areasDatas[value].split(",");
for(var i=0;i<areas.length;i++){
var option = document.createElement("option");
var v = areas[i].split("#");
option.value = v[0];
option.text = v[1];
areaDom.appendChild(option);
}
}
};
</script>
</body>
</html>
js 省市级联
最新推荐文章于 2020-05-24 13:00:09 发布