数据

data.js

html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>省市级联</title>
  7. </head>
  8. <body>
  9. <div class="box">
  10. <select name="" id="province"></select>
  11. <select name="" id="city"></select>
  12. <select name="" id="county"></select>
  13. </div>
  14. <script src="js/data.js"></script>
  15. <script>
  16. window.onload= function(){
  17. init();
  18. }
  19. function init(){
  20. //将省添加到province中
  21. let province_list = data.province_list
  22. let city_list = data.city_list
  23. let county_list = data.county_list
  24. let options = '<option value="" disabled selected>请选择</option>';
  25. for(let key in province_list){
  26. options += '<option value="' + key + '">' +province_list[key] + '</option>';
  27. }
  28. let province = document.querySelector('#province');
  29. province.innerHTML = options;
  30. province.onchange=function(){
  31. //取出省前面两个数字
  32. let pre = this.value.substr(0,2);
  33. //根据省前两位特征将所有的市添加到市的组件
  34. options = '<option value="" disabled selected>请选择</option>';
  35. for (let key in city_list) {
  36. if(key.substr(0,2) == pre){
  37. options += '<option value="' + key + '">' +city_list[key] + '</option>';
  38. }
  39. }
  40. console.log(options)
  41. let city = document.querySelector("#city")
  42. city.innerHTML = options;
  43. }
  44. city.onchange=function(){
  45. //取出省前面4个数字
  46. let pre = this.value.substr(0,4);
  47. //根据省前两位特征将所有的市添加到市的组件
  48. options = '';
  49. for (let key in county_list) {
  50. if(key.substr(0,4) == pre){
  51. options += '<option value="' + key + '">' +county_list[key] + '</option>';
  52. }
  53. }
  54. console.log(options)
  55. let county = document.querySelector("#county")
  56. county.innerHTML = options;
  57. }
  58. }
  59. </script>
  60. </body>
  61. </html>