abstract:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax实现三级级联动</t
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax实现三级级联动</title> </head> <body> 省:<select name="" id="pro"></select> 市:<select name="" id="city"></select> 区县:<select name="" id="area"></select> <!--<p><span id="addr1"></span ><span id="addr2"></span><span id="addr3"></span></p>--> <p id="addr"></p> <script src="lib/jquery-3.3.1.min.js"></script> <script> $(function () { $.getJSON('inc/1.json',function(data) { // console.log(data); let option='<option value="">选择(省)</option>'; $.each(data,function (i) { option+='<option value="'+data[i].proId+'">'+data[i].proName+'</option>' }); // console.log(option); $('#pro').html(option); }); $('#pro').change(function () { console.log($(this).find(':selected').text());//查看当前选择的省的名称 // $('#addr1').html($(this).find(':selected').text()); $('#addr').html($(this).find(':selected').text()); $.getJSON('inc/2.json',function(data){ // console.log(data); let option='<option value="">选择(市)</option>'; $.each(data,function (i) { if(data[i].proId == $('#pro').val()){ option+='<option value="'+data[i].cityId+'">'+data[i].cityName+'</option>' }}); // console.log(option); $('#city').html(option); }); }); $('#city').change(function () { console.log($(this).find(':selected').text());//查看当前选择的市的名称 // $('#addr2').html($(this).find(':selected').text()); $('#addr').html($('#pro').find(':selected').text()+$(this).find(':selected').text()); $.getJSON('inc/3.json',function(data){ // console.log(data); let option='<option value="">选择(县区)</option>'; $.each(data,function (i) { if(data[i].cityId == $('#city').val()){ option+='<option value="'+data[i].areaId+'">'+data[i].areaName+'</option>' } }); // console.log(option); $('#area').html(option); }); }) $('#area').change(function () { console.log($(this).find(':selected').text());//查看当前选择的县区的名称 // $('#addr3').html($(this).find(':selected').text()); $('#addr').html($('#pro').find(':selected').text()+$('#city').find(':selected').text()+$(this).find(':selected').text()); }); }) </script> </body> </html>
[ { "proId":1, "proName":"安徽" }, { "proId":2, "proName":"江苏" } ]
[ { "cityId":1, "cityName":"合肥", "proId":1 }, { "cityId":2, "cityName":"芜湖", "proId":1 }, { "cityId":3, "cityName":"南京", "proId":2 }, { "cityId":4, "cityName":"苏州", "proId":2 } ]
[ { "areaId":1, "areaName":"包河区", "cityId":1 }, { "areaId":2, "areaName":"蜀山区", "cityId":1 }, { "areaId":1, "areaName":"玄武区", "cityId":3 }, { "areaId":2, "areaName":"昆山市", "cityId":3 }, { "areaId":1, "areaName":"镜湖区", "cityId":2 }, { "areaId":2, "areaName":"弋江区", "cityId":2 }, { "areaId":1, "areaName":"虎丘区", "cityId":4 }, { "areaId":2, "areaName":"吴中区", "cityId":4 } ]
ajax实现三级联动实现比在html里直接写方便多了,只要修改三个JSON文件就可以,传输方式用的是$.getJSON(),里面是地址和函数,实现页面实时显示我想了2种方法,1.是在html中加入3个span标签,写3个分别进行地址的输出,2.是在ajax代码中使用+连接符进行连接输出
Correcting teacher:韦小宝Correction time:2018-12-26 09:55:46
Teacher's summary:不错不错!写的很棒!也很有想法!课后记得多练习哦!