select.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. layui.use('form', function() {
  2. var form = layui.form;
  3. var province = $("#province"),
  4. city = $("#city"),
  5. district = $("#district");
  6. //初始将省份数据赋予
  7. for (var i = 0; i < provinceList.length; i++) {
  8. addEle(province, provinceList[i].name);
  9. }
  10. //赋予完成 重新渲染select
  11. form.render('select');
  12. //向select中 追加内容
  13. function addEle(ele, value) {
  14. var optionStr = "";
  15. optionStr = "<option value=" + value + " >" + value + "</option>";
  16. ele.append(optionStr);
  17. }
  18. //移除select中所有项 赋予初始值
  19. function removeEle(ele) {
  20. ele.find("option").remove();
  21. var optionStar = "<option value=" + "0" + ">" + "请选择" + "</option>";
  22. ele.append(optionStar);
  23. }
  24. var provinceText,
  25. cityText,
  26. cityItem;
  27. //选定省份后 将该省份的数据读取追加上
  28. form.on('select(province)', function(data) {
  29. provinceText = data.value;
  30. $.each(provinceList, function(i, item) {
  31. if (provinceText == item.name) {
  32. cityItem = i;
  33. return cityItem;
  34. }
  35. });
  36. removeEle(city);
  37. removeEle(district);
  38. $.each(provinceList[cityItem].cityList, function(i, item) {
  39. addEle(city, item.name);
  40. })
  41. //重新渲染select
  42. form.render('select');
  43. })
  44. ////选定市或直辖县后 将对应的数据读取追加上
  45. form.on('select(city)', function(data) {
  46. cityText = data.value;
  47. removeEle(district);
  48. $.each(provinceList, function(i, item) {
  49. if (provinceText == item.name) {
  50. cityItem = i;
  51. return cityItem;
  52. }
  53. });
  54. $.each(provinceList[cityItem].cityList, function(i, item) {
  55. if (cityText == item.name) {
  56. for (var n = 0; n < item.areaList.length; n++) {
  57. addEle(district, item.areaList[n]);
  58. }
  59. }
  60. })
  61. //重新渲染select
  62. form.render('select');
  63. })
  64. })