JQuery 二级菜单联动,遍历($.each())

JQuery 二级菜单联动,遍历($.each())

遍历: $.each(数组或集合,fun(index,item){ })

  1. <!DOCTYPE html>

  2. <html xmlns="http://www.w3.org/1999/xhtml">

  3. <head>

  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

  5. <title></title>

  6. <script src="scripts/jquery-1.7.1.min.js"></script>

  7. <script>

  8. //$.each(obj,fun(i,n))

  9. //如果obj是数组,则i是索引,n是元素

  10. //如果obj是对象或键值对,i是键,n是值

    扫描二维码关注公众号,回复: 3200697 查看本文章
  11.  
  12. //定义省市数据,键值对集合

  13. var datas = {

  14. "北京": ["朝阳", "海淀", "昌平", "丰台"],

  15. "山东": ["青岛", "济南", "烟台"],

  16. "山西": ["大同", "太原", "运城", "长治"],

  17. "河南": ["洛阳", "开封", "郑州", "驻马店"],

  18. "河北": ["石家庄", "张家口", "保定"]

  19. };

  20. $(function() {

  21. //创建省的select

  22. var select = $('<select id="selectProvince"></select>'); //创建JQuery的标签对象。

  23. //最后写change事件:为省的select绑定change事件

  24. select.change(function () {

  25. //找到市信息

  26. var citys = datas[$(this).val()];

  27. //删除市的原有option

  28. $('#selectCity').empty();

  29. //添加option

  30. $.each(citys, function(index,item) {

  31. $('<option>' + item + '</option>').appendTo('#selectCity');

  32. });

  33. });

  34. //追加到body中

  35. select.appendTo('body');

  36. //遍历集合

  37. $.each(datas, function (key, value) {

  38. //根据数据创建option并追加到select上

  39. $('<option value="' + key + '">' + key + '</option>').appendTo(select);

  40.  
  41. });

  42.  
  43. //创建市的select

  44. var selectCity = $('<select id="selectCity"></select>').appendTo('body');

  45. //获取选中的省信息

  46. var pro = $('#selectProvince').val();

  47. //将省名称作为键到集合中获取值

  48. var citys = datas[pro];

  49. //遍历市的数组

  50. $.each(citys, function(index, item) {

  51. $('<option>' + item + '</option>').appendTo(selectCity);

  52. });

  53. });

  54. </script>

  55. </head>

  56. <body>

  57.  
  58. </body>

  59. </html>

  60.  

猜你喜欢

转载自blog.csdn.net/qq_34802511/article/details/82505750