JQuery實現省市區的三級聯動
阿新 • • 發佈:2019-03-20
分享 選擇 tro java html select 實現 select標簽 文檔加載
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 varcity=[ 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文檔操作要對比學習
JQuery實現省市區的三級聯動