JQuery实现省市区的三级联动
程序员文章站
2023-11-28 09:22:22
实现结果: 注: 需要掌握jQuery选择器,基本语法,事件,DOM属性等知识 对jQuery文档操作要对比学习 ......
1 <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 5 <title>insert title here</title> 6 <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script> 7 <script type="text/javascript"> 8 /*添加省*/ 9 var province=["湖北省","吉林省","河北省","海南省"]; 10 $(document).ready(function(){ 11 //当文档加载结束在div标签后添加select列表 12 $("div").after("<select><option>请选择省</option></select>"); 13 $("select").attr("id","pro"); 14 for(var i = 0; i < province.length; i++){ 15 //获取select标签下的最后一个option标签并在后面不断添加option选项直到循环结束 16 $('#pro option:last').after("<option>"+province[i]+"</option"); 17 } 18 }) 19 /*添加市*/ 20 var city=[ 21 ["襄阳市","武汉市","荆州市"], 22 ["长春市","吉林市","榆树市"], 23 ["唐山市","石家庄市","秦皇岛市"], 24 ["沙市区","荆州区"] 25 ]; 26 var town=[ 27 [ 28 ["襄州区","襄城区","樊城市"], 29 ["武昌区","江汉区","江夏区"], 30 ["襄阳市","武汉市","荆州市"] 31 ], 32 [ 33 ["朝阳区","南关区","宽城区"], 34 ["龙潭区","船营区","昌邑区"], 35 ["正阳街道","培英街道","华昌街道"] 36 ], 37 [ 38 ["路南区","路北区","古冶区"], 39 ["长安区","桥西区","新华区"], 40 ["海港区","山海关区","北戴河区"] 41 ], 42 [ 43 ["秀英区","琼山区","美兰区"], 44 ["西沙群岛","中沙群岛","南沙群岛"], 45 ["海棠区","吉阳区","天涯区"] 46 ] 47 ] 48 $(document).ready(function(){ 49 //当文档加载结束在div标签后添加select列表 50 $("#pro").after("<select><option>请选择市</option></select"); 51 $("select:contains(请选择市)").attr("id","cit"); 52 $("#cit").after("<select><option>请选择区</option></select"); 53 $("select:contains(请选择区)").attr("id","two"); 54 $("#pro option").click(function(){ 55 var indexo=$("option").index($(this)); 56 if(indexo == 0){ 57 //替换原来select中的内容 58 $("#cit").replacewith("<select><option>请选择市</option></select"); 59 //此处会将select的id属性清空,故需要再次赋给id属性 60 $("select:contains(请选择市)").attr("id","cit"); 61 $("#two").replacewith("<select><option>请选择区</option></select"); 62 $("select:contains(请选择区)").attr("id","two"); 63 } 64 else{ 65 var cityy = city[indexo-1]; 66 var townn = town[indexo-1]; 67 var townl = townn[0]; 68 //清空样式 69 $("#two").empty(); 70 $("#cit").empty(); 71 console.log(townn); 72 for(var i = 0; i < cityy.length; i++){ 73 $('#cit').append("<option>"+cityy[i]+"</option"); 74 } 75 for(var i = 0; i < townl.length; i++){ 76 //当未选择市的时候,自动将第一个市下的区放入select中 77 $('#two').append("<option>"+townl[i]+"</option"); 78 } 79 $("#cit option").click(function(){ 80 var indext=$("#cit option").index($(this)); 81 var townm = townn[indext]; 82 $("#two").empty(); 83 for(var i = 0; i < townm.length; i++){ 84 $('#two').append("<option>"+townm[i]+"</option"); 85 } 86 }) 87 } 88 }) 89 }) 90 </script> 91 </head> 92 <body> 93 <div></div> 94 </body> 95 </html>
实现结果:
注:
需要掌握jquery选择器,基本语法,事件,dom属性等知识
对jquery文档操作要对比学习
上一篇: javascript中BOM基础知识总结
下一篇: jQuery实现轮播图