jQuery 省市三级联动
页面打开默认获取省信息,选择省以后,再获取市信息,点击市以后,再获取地区信息
1var regions = {2 state: $('#state'),3 city: $('#city'),4 district: $('#district'),5 init: function () {6 var _this = this7 _this.getState(_this.state, 1)8 _this.state.change(function () {9 var id = $(this).val()10 _this.city.find('option:gt(0)').remove()11 _this.district.find('option:gt(0)').remove()12 _this.getCity(_this.city, id)13 })1415 _this.city.change(function () {16 var id = $(this).val()17 _this.district.find('option:gt(0)').remove()18 _this.getDistrict(_this.district, id)19 })20 },21 getState: function (elem, id, callback) {22 this.getJson(elem, id, callback)23 },24 getCity: function (elem, id, callback) {25 this.getJson(elem, id, callback)26 },27 getDistrict: function (elem, id, callback) {28 this.getJson(elem, id, callback)29 },30 render: function (elem, data, callback) {31 if (data.regions && !$.isEmptyObject(data.regions)) {32 elem.find('option:gt(0)').remove()33 $.each(data.regions, function (name, value) {34 elem.append(35 '<option value ="' + value.id + '">' + value.name + '</option>'36 )37 })38 if (callback && typeof callback == 'function') {39 callback()40 }41 }42 },43 getJson: function (elem, id, callback) {44 var _this = this45 $.ajax({46 type: 'post',47 url: system.url('address/get-regions'),48 data: {49 parent_id: id,50 },51 dataType: 'json',52 cache: false,53 success: function (resp) {54 if (resp.status) {55 _this.render(elem, resp.data, callback)56 }57 },58 error: function () {},59 })60 },61}
callback的作用
当获取信息时,需要渲染对应的省市信息 通过添加回调,可以依次获取省、市、地区信息
1regions.getState(regions.state, 1, function () {2 $('#state').val(_this.attr('data-state'))3 regions.getCity(regions.city, _this.attr('data-state'), function () {4 $('#city').val(_this.attr('data-city'))5 regions.getDistrict(regions.district, _this.attr('data-city'), function () {6 $('#district').val(_this.attr('data-district'))7 })8 })9})
暂无评论,来抢沙发吧。