JavaScript development three-level linkage core JS
This chapter introduces the most critical JS code. Without further explanation, let’s look at the code first:
<script> //聲明省 var oProc = ["安徽","上海","山東"]; //直接聲明array //聲明市 var oCity = [ ["合肥","淮南","蕪湖"], ["浦東","閔行","浦西"], ["濟(jì)南","青島","棗莊"] ]; //聲明區(qū) var oDist = [ [ ["政務(wù)區(qū)","廬陽區(qū)","蜀山區(qū)"], ["田家庵區(qū)","大通區(qū)","九龍崗區(qū)"], ["鏡湖區(qū)","鳩江區(qū)","三山區(qū)"] ], [ ["浦東1","浦東2","浦東3"], ["閔行1","閔行2","閔行3"], ["浦西1","浦西","浦西3"] ], [ ["歷下區(qū)","天橋區(qū)","長清區(qū)"], ["市南區(qū)","市北區(qū)","李滄區(qū)"], ["薛城區(qū)","市中區(qū)","嶧城區(qū)"] ] ]; var oproc = document.getElementById("proc"); var ocity = document.getElementById("city"); var odist = document.getElementById("dist"); window.onload = function(){ for(var i =0;i<oProc.length;i++){ //創(chuàng)建元素節(jié)點 var oOpt = document.createElement("option"); //創(chuàng)建文本節(jié)點 var oTxt = document.createTextNode(oProc[i]); oOpt.appendChild(oTxt); oproc.appendChild(oOpt); } }; function showCity(){ if(oproc.value=="-1"){ ocity.options.length = 1; odist.options.length = 1; }else{ ocity.options.length = 1; odist.options.length = 1; var num = oproc.options.selectedIndex; //console.log(num); 測試是否成功 for(var i =0;i<oCity[num-1].length;i++){ var oOpt = document.createElement("option"); var oTxt = document.createTextNode(oCity[num-1][i]); oOpt.appendChild(oTxt); ocity.appendChild(oOpt); } } } function showDist(){ if(ocity.value=='-1'){ odist.options.length = 1 }else{ odist.options.length = 1; var numPro = oproc.options.selectedIndex; var numCity = ocity.options.selectedIndex; for(var i=0;i<oDist[numPro-1][numCity-1].length;i++){ var oOpt = document.createElement("option"); var oTxt = document.createTextNode(oDist[numPro-1][numCity-1][i]); oOpt.appendChild(oTxt); odist.appendChild(oOpt); } } } </script>
for(var i =0;i<oCity[num-1].length;i++)This The place is a bit complicated and you may not understand it. Please explain: What does [num-1] mean and why is it reduced by 1?
We use console.log(num) to test it. The results obtained are 1, 2, 3, and the starting value of our array is 0, so we need to subtract 1. For example, we select Anhui. Anhui ranks first in the array, but the starting subscript is 0. The value we get using
selectedIndex is 1. Therefore, if we want to get Anhui, we only need to Can be reduced by 1.