经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » jQuery » 查看文章
3.省市区,三级联动(优化版)
来源:cnblogs  作者:[蒙面大侠缺颗牙]  时间:2019/5/14 8:49:45  对本文有异议

  1. 1 <body onload="change()">
  2. 2 <form>
  3. 3 <select onchange="sel_one()">
  4. 4 </select>
  5. 5 <select onchange="sel_two()">
  6. 6 <option>请选择所在的城市</option>
  7. 7 </select>
  8. 8 <select>
  9. 9 <option>请选择所在的县区</option>
  10. 10 </select>
  11. 11 </form>
  12. 12 <script>
  13. 13 var select = document.getElementsByTagName('select');
  14. 14 var sel_1 = select[0];
  15. 15 var sel_2 = select[1];
  16. 16 var sel_3 = select[2];
  17. 17 var oAjax = new XMLHttpRequest();
  18. 18 var c = '';
  19. 19 function change() {
  20. 20 oAjax.open('GET', 'json/city.json', true);
  21. 21 oAjax.send();
  22. 22 oAjax.onreadystatechange = function () {
  23. 23 if (oAjax.readyState == 4 && oAjax.status == 200) {
  24. 24 c = JSON.parse(oAjax.responseText);
  25. 25 var option_1 = '<option>请选择所在的省市</option>';
  26. 26 for (var i = 0; i < c.city.length; i++) {
  27. 27 option_1 += '<option>' + c.city[i].name + '</option>';
  28. 28 }
  29. 29 sel_1.innerHTML = option_1;
  30. 30 }
  31. 31 }
  32. 32 }
  33. 33 function sel_one() {
  34. 34 sel_1.firstElementChild.style.display = 'none';
  35. 35 sel_3.innerHTML = '<option>请选择所在的县区</option>';
  36. 36 var index = sel_1.selectedIndex - 1;
  37. 37 if (sel_1.value == c.city[index].name) {
  38. 38 var option_2 = '';
  39. 39 for (var i = 0; i < c.city[index].city.length; i++) {
  40. 40 option_2 += '<option>' + c.city[index].city[i].name + '</option>';
  41. 41 }
  42. 42 sel_2.innerHTML = option_2;
  43. 43 }
  44. 44 sel_two();
  45. 45 }
  46. 46 function sel_two() {
  47. 47 var index = sel_1.selectedIndex - 1;
  48. 48 var index2 = sel_2.selectedIndex;
  49. 49 if (sel_2.value == c.city[index].city[index2].name) {
  50. 50 var option_3 = ''
  51. 51 for (var i = 0; i < c.city[index].city[index2].area.length; i++) {
  52. 52 option_3 += '<option>' + c.city[index].city[index2].area[i] + '</option>';
  53. 53 }
  54. 54 sel_3.innerHTML = option_3;
  55. 55 }
  56. 56 }
  57. 57 </script>
  58. 58 </body>

 

原文链接:http://www.cnblogs.com/web-xpy/p/10856239.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号