首页 > 代码库 > js三级联动
js三级联动
原生js实现省市区三级联动
html部分代码
<select name="" id="p">
<option value="http://www.mamicode.com/0">请选择省</option>
</select>
<select name="" id="c">
<option value="http://www.mamicode.com/0">请选择市</option>
</select>
<select name="" id="a">
<option value="http://www.mamicode.com/0">请选择区</option>
</select>
js代码
(function(doc) { if(data.code == 200) { var result = data.result; var poption, coption, aoption; for(var i = 0; i < result.length; i++) { poption = new Option(result[i].name, result[i].id); doc.querySelector("#p").options.add(poption); } //省点击事件 doc.querySelector("#p").addEventListener("change", function() { doc.querySelector("#c").length = 1; doc.querySelector("#a").length = 1; var pval = this.value; for(var i = 0; i < result.length; i++) { if(result[i].id == pval) { var city = result[i].child; for(var j = 0; j < city.length; j++) { coption = new Option(city[j].name, city[j].id); doc.querySelector("#c").options.add(coption); } return; } } }); //市的点击事件 doc.querySelector("#c").addEventListener("change", function() { doc.querySelector("#a").length = 1; var cval = this.value; for(var i = 0; i < result.length; i++) { var city = result[i].child; for(var j = 0; j < city.length; j++) { if(city[j].id == cval) { var aera = city[j].child; for(var k = 0; k < aera.length; k++) { aoption = new Option(aera[k].name, aera[k].id); doc.querySelector("#a").options.add(aoption); } } } } }); } }(document));
json数据
var data =http://www.mamicode.com/ { "code": "200", "msg": "success", "result": [ { "id": "01", "name": "江苏省", "child": [ { "id": "011", "name": "南京市", "child": [ { "id": "0111", "name": "雨花台区" }, { "id": "0112", "name": "秦淮区" }, { "id": "0113", "name": "玄武区" }, { "id": "0114", "name": "白下区" } ] }, { "id": "012", "name": "苏州市", "child": [ { "id": "0121", "name": "吴中区" }, { "id": "0122", "name": "姑苏区" }, { "id": "0123", "name": "高新区" }, { "id": "0124", "name": "开发区" } ] }, { "id": "013", "name": "扬州市", "child": [ { "id": "0131", "name": "第一区" }, { "id": "0132", "name": "第二区" }, { "id": "0133", "name": "第三区" }, { "id": "0134", "name": "第四区" } ] } ] }, { "id": "02", "name": "浙江省", "child": [ { "id": "021", "name": "杭州市", "child": [ { "id": "0211", "name": "雨花台区" }, { "id": "0212", "name": "秦淮区" }, { "id": "0213", "name": "玄武区" }, { "id": "0214", "name": "白下区" } ] }, { "id": "022", "name": "宁波市", "child": [ { "id": "0221", "name": "吴中区" }, { "id": "0222", "name": "姑苏区" }, { "id": "0223", "name": "高新区" }, { "id": "0224", "name": "开发区" } ] }, { "id": "023", "name": "温州市", "child": [ { "id": "0231", "name": "第一区" }, { "id": "0232", "name": "第二区" }, { "id": "0233", "name": "第三区" }, { "id": "0234", "name": "第四区" } ] } ] } ] }
js三级联动
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。