最近公司做的项目要和京东的数据做对接,所以要做个类似京东商品的详情页。页面的数据,是可以从京东接口获取到的,但是地址插件选择的效果需要自己实现。前端的同事在之前的项目中,已经选择了一款地址插件(city-picker.js),但是这款插件最多只支持三级地址,而且最主要的是这插件的地址数据来源,是写死在一个json文件中的,意思就是说,在使用这个插件的时候页面要一次性的把所有的地址数据都加载出来,这在pc端一般倒还可以承受,但是到了,移动端,随便一个手机就会卡死,浏览器直接崩溃。
经过在网上的各种查找,和研究,发现一个博客,http://www.cnblogs.com/huangchanghuan/p/6681510.html
对city-picker这个插件进行了扩展,扩展成了支持四级地址的插件了。这正是我想要的,因为京东给过来的地址数据就是4级的。正好可以使用。然后就拿过来直接用了。
很强大,完美的满足了,我的需求。但是这个大神的博客只是将三级地址改造成了四级地址,没有解决,动态加载数据的问题,就是说用这个四级地址插件的时候,还是要把京东的地址库数据转成json文件一次性加载到页面。这样的话在移动端浏览时还是会把浏览器搞崩。
好了,说了这么多铺垫的废话,就是为了引出,我对这个四级地址插件的改造。
直接代码
/*!
* CityPicker v@VERSION
* https://github.com/tshi0912/citypicker
*
* Copyright (c) 2015-@YEAR Tao Shi
* Released under the MIT license
*
* Date: @DATE
*/ ChineseDistricts={
13 "86": {
14 "中国": [
15 {
16 "address": "北京",
17 "code": "1"
18 },
19 {
20 "address": "上海",
21 "code": "2"
22 },
23 {
24 "address": "天津",
25 "code": "3"
26 },
27 {
28 "address": "重庆",
29 "code": "4"
30 },
31 {
32 "address": "河北",
33 "code": "5"
34 },
35 {
36 "address": "山西",
37 "code": "6"
38 },
39 {
40 "address": "河南",
41 "code": "7"
42 },
43 {
44 "address": "辽宁",
45 "code": "8"
46 },
47 {
48 "address": "吉林",
49 "code": "9"
50 },
51 {
52 "address": "黑龙江",
53 "code": "10"
54 },
55 {
56 "address": "内蒙古",
57 "code": "11"
58 },
59 {
60 "address": "江苏",
61 "code": "12"
62 },
63 {
64 "address": "山东",
65 "code": "13"
66 },
67 {
68 "address": "安徽",
69 "code": "14"
70 },
71 {
72 "address": "浙江",
73 "code": "15"
74 },
75 {
76 "address": "福建",
77 "code": "16"
78 },
79 {
80 "address": "湖北",
81 "code": "17"
82 },
83 {
84 "address": "湖南",
85 "code": "18"
86 },
87 {
88 "address": "广东",
89 "code": "19"
90 },
91 {
92 "address": "广西",
93 "code": "20"
94 },
95 {
96 "address": "江西",
97 "code": "21"
98 },
99 {
100 "address": "四川",
101 "code": "22"
102 },
103 {
104 "address": "海南",
105 "code": "23"
106 },
107 {
108 "address": "贵州",
109 "code": "24"
110 },
111 {
112 "address": "云南",
113 "code": "25"
114 },
115 {
116 "address": "*",
117 "code": "26"
118 },
119 {
120 "address": "陕西",
121 "code": "27"
122 },
123 {
124 "address": "甘肃",
125 "code": "28"
126 },
127 {
128 "address": "青海",
129 "code": "29"
130 },
131 {
132 "address": "宁夏",
133 "code": "30"
134 },
135 {
136 "address": "*",
137 "code": "31"
138 },
139 {
140 "address": "*",
141 "code": "32"
142 },
143 {
144 "address": "钓鱼岛",
145 "code": "84"
146 },
147 {
148 "address": "港澳",
149 "code": "52993"
150 }
151 ]
152 }
153 }; (function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery', 'ChineseDistricts'], factory);
} else if (typeof exports === 'object') {
// Node / CommonJS
factory(require('jquery'), require('ChineseDistricts'));
} else {
// Browser globals.
factory(jQuery, ChineseDistricts);
}
})(function ($, ChineseDistricts) { 'use strict';
if (typeof ChineseDistricts === 'undefined') {
throw new Error('The file "city-picker.data.js" must be included first!');
}
var NAMESPACE = 'citypicker';
var EVENT_CHANGE = 'change.' + NAMESPACE;
var PROVINCE = 'province';
var CITY = 'city';
var DISTRICT = 'district';
var COUNTY = 'county'; function CityPicker(element, options) {
this.$element = $(element);
this.$dropdown = null;
this.options = $.extend({}, CityPicker.DEFAULTS, $.isPlainObject(options) && options);
this.active = false;
this.dems = [];
this.needBlur = false;
this.init();
} CityPicker.prototype = {
constructor: CityPicker, init: function () { this.defineDems(); this.render(); this.bind(); this.active = true;
},
//界面显示处理
render: function () {
var p = this.getPosition(),
placeholder = this.$element.attr('placeholder') || this.options.placeholder,
textspan = '<span class="city-picker-span" style="' +
this.getWidthStyle(p.width) + 'height:' +
p.height + 'px;line-height:' + (p.height - 1) + 'px;">' +
(placeholder ? '<span class="placeholder">' + placeholder + '</span>' : '') +
'<span class="title"></span><div class="arrow"></div>' + '</span>', dropdown = '<div class="city-picker-dropdown" style="left:0px;top:100%;' +
this.getWidthStyle(p.width, true) + '">' +
'<div class="city-select-wrap">' +
'<div class="city-select-tab">' +
'<a class="active" data-count="province">省份</a>' +
(this.includeDem('city') ? '<a data-count="city">城市</a>' : '') +
(this.includeDem('district') ? '<a data-count="district">区县</a>' : '') +
(this.includeDem('county') ? '<a data-count="county">乡镇</a>' : '') +
'</div>' +
'<div class="city-select-content">' +
'<div class="city-select province" data-count="province"></div>' +
(this.includeDem('city') ? '<div class="city-select city" data-count="city"></div>' : '') +
(this.includeDem('district') ? '<div class="city-select district" data-count="district"></div>' : '') +
(this.includeDem('county') ? '<div class="city-select county" data-count="county"></div>' : '') +
'</div></div>'; this.$element.addClass('city-picker-input');
this.$textspan = $(textspan).insertAfter(this.$element);
this.$dropdown = $(dropdown).insertAfter(this.$textspan);
var $select = this.$dropdown.find('.city-select'); // setup this.$province, this.$city and/or this.$district object
$.each(this.dems, $.proxy(function (i, type) {
this['$' + type] = $select.filter('.' + type + '');
}, this)); this.refresh();
}, refresh: function (force) {
// clean the data-item for each $select
var $select = this.$dropdown.find('.city-select');
$select.data('item', null);
// parse value from value of the target $element
var val = this.$element.val() || '';
val = val.split('/');
$.each(this.dems, $.proxy(function (i, type) {//遍历dems
if (val[i] && i < val.length) {
this.options[type] = val[i];//把当前显示值赋值给options
} else if (force) {
this.options[type] = '';
}
this.output(type);//输出下拉框显示数据
}, this));
this.tab(PROVINCE);
this.feedText();//界面显示选择的内容
this.feedVal();//input标签value赋值
},
//dems赋值
defineDems: function () {
var stop = false;
$.each([PROVINCE, CITY, DISTRICT,COUNTY], $.proxy(function (i, type) {
if (!stop) {
this.dems.push(type);
}
if (type === this.options.level) {
stop = true;
}
}, this));
}, includeDem: function (type) {
return $.inArray(type, this.dems) !== -1;
}, getPosition: function () {
var p, h, w, s, pw;
p = this.$element.position();
s = this.getSize(this.$element);
h = s.height;
w = s.width;
if (this.options.responsive) {
pw = this.$element.offsetParent().width();
if (pw) {
w = w / pw;
if (w > 0.99) {
w = 1;
}
w = w * 100 + '%';
}
} return {
top: p.top || 0,
left: p.left || 0,
height: h,
width: w
};
}, getSize: function ($dom) {
var $wrap, $clone, sizes;
if (!$dom.is(':visible')) {
$wrap = $("<div />").appendTo($("body"));
$wrap.css({
"position": "absolute !important",
"visibility": "hidden !important",
"display": "block !important"
}); $clone = $dom.clone().appendTo($wrap); sizes = {
width: $clone.outerWidth(),
height: $clone.outerHeight()
}; $wrap.remove();
} else {
sizes = {
width: $dom.outerWidth(),
height: $dom.outerHeight()
};
} return sizes;
}, getWidthStyle: function (w, dropdown) {
if (this.options.responsive && !$.isNumeric(w)) {
return 'width:' + w + ';';
} else {
return 'width:' + (dropdown ? Math.max(320, w) : w) + 'px;';
}
},
//绑定事件
bind: function () {
var $this = this;
$(document).on('click', (this._mouteclick = function (e) {
var $target = $(e.target);
var $dropdown, $span, $input;
if ($target.is('.city-picker-span')) {
$span = $target;
} else if ($target.is('.city-picker-span *')) {
$span = $target.parents('.city-picker-span');
}
if ($target.is('.city-picker-input')) {
$input = $target;
}
if ($target.is('.city-picker-dropdown')) {
$dropdown = $target;
} else if ($target.is('.city-picker-dropdown *')) {
$dropdown = $target.parents('.city-picker-dropdown');
}
if ((!$input && !$span && !$dropdown) ||
($span && $span.get(0) !== $this.$textspan.get(0)) ||
($input && $input.get(0) !== $this.$element.get(0)) ||
($dropdown && $dropdown.get(0) !== $this.$dropdown.get(0))) {
$this.close(true);
}
}));
this.$element.on('change', (this._changeElement = $.proxy(function () {
this.close(true);
this.refresh(true);
}, this))).on('focus', (this._focusElement = $.proxy(function () {
this.needBlur = true;
this.open();
}, this))).on('blur', (this._blurElement = $.proxy(function () {
if (this.needBlur) {
this.needBlur = false;
this.close(true);
}
}, this)));
this.$textspan.on('click', function (e) {
var $target = $(e.target), type;
$this.needBlur = false;
if ($target.is('.select-item')) {
type = $target.data('count');
$this.open(type);
} else {
if ($this.$dropdown.is(':visible')) {
$this.close();
} else {
$this.open();
}
}
}).on('mousedown', function () {
$this.needBlur = false;
});
this.$dropdown.on('click', '.city-select a', function () {
var $select = $(this).parents('.city-select');
var $active = $select.find('a.active');
var last = $select.next().length === 0;
$active.removeClass('active');
$(this).addClass('active');
if ($active.data('code') !== $(this).data('code')) {
$select.data('item', {
address: $(this).attr('title'), code: $(this).data('code')
});
$(this).trigger(EVENT_CHANGE);
$this.feedText();
$this.feedVal(true);
if (last) {
$this.close();
}
}
}).on('click', '.city-select-tab a', function () {
if (!$(this).hasClass('active')) {
var type = $(this).data('count');
$this.tab(type);
}
}).on('mousedown', function () {
$this.needBlur = false;
});
if (this.$province) {
this.$province.on(EVENT_CHANGE, (this._changeProvince = $.proxy(function () {
if(this.output(CITY)){//判断下一个tab是否有数据,没有则关闭下拉
$this.close();
return;
};
422 this.output(CITY);
423 this.output(DISTRICT);
424 this.output(COUNTY);
this.tab(CITY);
}, this)));
}
if (this.$city) {
this.$city.on(EVENT_CHANGE, (this._changeCity = $.proxy(function () {
if(this.output(DISTRICT)){
$this.close();
return;
};
this.output(COUNTY);
this.tab(DISTRICT);
}, this)));
} if (this.$district) {
this.$district.on(EVENT_CHANGE, (this._changeDistrict = $.proxy(function () {
if(this.output(COUNTY)){
$this.close();
return;
};
this.tab(COUNTY);
}, this)));
}
},
//显示下拉
open: function (type) {
type = type || PROVINCE;
this.$dropdown.show();
this.$textspan.addClass('open').addClass('focus');
this.tab(type);
},
//关闭下拉
close: function (blur) {
this.$dropdown.hide();
this.$textspan.removeClass('open');
if (blur) {
this.$textspan.removeClass('focus');
}
},
//解绑事件
unbind: function () { $(document).off('click', this._mouteclick); this.$element.off('change', this._changeElement);
this.$element.off('focus', this._focusElement);
this.$element.off('blur', this._blurElement); this.$textspan.off('click');
this.$textspan.off('mousedown'); this.$dropdown.off('click');
this.$dropdown.off('mousedown'); if (this.$province) {
this.$province.off(EVENT_CHANGE, this._changeProvince);
} if (this.$city) {
this.$city.off(EVENT_CHANGE, this._changeCity);
} if (this.$district) {
this.$district.off(EVENT_CHANGE, this._changeDistrict);
}
},
//获取选择项信息
getText: function () {
var text = '';
this.$dropdown.find('.city-select')
.each(function () {
var item = $(this).data('item'),
type = $(this).data('count');
if (item) {
text += ($(this).hasClass('province') ? '' : '/') + '<span class="select-item" data-count="' +
type + '" data-code="' + item.code + '">' + item.address + '</span>';
}
});
return text;
},
getPlaceHolder: function () {
return this.$element.attr('placeholder') || this.options.placeholder;
},
//显示placeholder或者选择的区域
feedText: function () {
var text = this.getText();
if (text) {
this.$textspan.find('>.placeholder').hide();
this.$textspan.find('>.title').html(this.getText()).show();
} else {
this.$textspan.find('>.placeholder').text(this.getPlaceHolder()).show();
this.$textspan.find('>.title').html('').hide();
}
},
getCode: function (count) {
var obj = {}, arr = [];
this.$textspan.find('.select-item')
.each(function () {
var code = $(this).data('code');
var count = $(this).data('count');
obj[count] = code;
arr.push(code);
});
return count ? obj[count] : arr.join('/');
},
getVal: function () {
var text = '';
var code='';
this.$dropdown.find('.city-select')
.each(function () {
var item = $(this).data('item');
if (item) {
text += ($(this).hasClass('province') ? '' : '/') + item.address;
code += ($(this).hasClass('province') ? '' : '_') + item.code;
}
});
$("#addrValue").val(code);
return text;
},
//input的value赋值
feedVal: function (trigger) {
this.$element.val(this.getVal());
if(trigger) {
this.$element.trigger('cp:updated');
}
},
//输出数据
output: function (type) {
var $this = this;
var options = this.options;
//var placeholders = this.placeholders;
var $select = this['$' + type];
var data = type === PROVINCE ? {} : [];
var item;
var districts;
var code;
var matched = null;
var value;
if (!$select || !$select.length) {
return;
}
item = $select.data('item');
value = (item ? item.address : null) || options[type];
code = (
type === PROVINCE ? 86 :
type === CITY ? this.$province && this.$province.find('.active').data('code') :
type === DISTRICT ? this.$city && this.$city.find('.active').data('code') :
type === COUNTY ? this.$district && this.$district.find('.active').data('code') : code
);
//districts = $.isNumeric(code) ? ChineseDistricts[code] : null;
//判断是否应该去远程加载数据
districts = $.isNumeric(code) ? this.remoteLoadData(type,code) : null;
if ($.isPlainObject(districts)) {
$.each(districts, function (code, address) {
var provs;
if (type === PROVINCE) {
provs = [];
for (var i = 0; i < address.length; i++) {
if (address[i].address === value) {
matched = {
code: address[i].code,
address: address[i].address
};
}
provs.push({
code: address[i].code,
address: address[i].address,
selected: address[i].address === value
});
}
data[code] = provs;
} else {
if (address === value) {
matched = {
code: code,
address: address
};
}
data.push({
code: code,
address: address,
selected: address === value
});
}
});
} $select.html(type === PROVINCE ? this.getProvinceList(data) :
this.getList(data, type));
$select.data('item', matched);//当前tab添加item(包含选择对象的内容)
if(! (type === PROVINCE)){//标识:下一个选项没有数据则关闭
if(data.length==0){
return true;
}
}
},
//遍历省份
getProvinceList: function (data) {
var list = [],
$this = this,
simple = this.options.simple; $.each(data, function (i, n) {
list.push('<dl class="clearfix">');
list.push('<dt>' + i + '</dt><dd>');
$.each(n, function (j, m) {
list.push(
'<a' +
' title="' + (m.address || '') + '"' +
' data-code="' + (m.code || '') + '"' +
' class="' +
(m.selected ? ' active' : '') +
'">' +
( simple ? $this.simplize(m.address, PROVINCE) : m.address) +
'</a>');
});
list.push('</dd></dl>');
}); return list.join('');
},
//遍历市或区或县
getList: function (data, type) {
var list = [],
$this = this,
simple = this.options.simple;
list.push('<dl class="clearfix"><dd>'); $.each(data, function (i, n) {
list.push(
'<a' +
' title="' + (n.address || '') + '"' +
' data-code="' + (n.code || '') + '"' +
' class="' +
(n.selected ? ' active' : '') +
'">' +
( simple ? $this.simplize(n.address, type) : n.address) +
'</a>');
});
list.push('</dd></dl>'); return list.join('');
},
//简化名字
simplize: function (address, type) {
address = address || '';
if (type === PROVINCE) {
return address.replace(/[省,市,自治区,壮族,回族,*]/g, '');
} else if (type === CITY) {
return address.replace(/[市,地区,回族,蒙古,苗族,白族,傣族,景颇族,藏族,彝族,壮族,傈僳族,布依族,侗族]/g, '')
.replace('哈萨克', '').replace('自治州', '').replace(/自治县/, '');
} else if (type === DISTRICT) {
return address.length > 2 ? address.replace(/[市,区,县,旗]/g, '') : address;
}
},
//处理tab显示
tab: function (type) {
var $selects = this.$dropdown.find('.city-select');
var $tabs = this.$dropdown.find('.city-select-tab > a');
var $select = this['$' + type];
var $tab = this.$dropdown.find('.city-select-tab > a[data-count="' + type + '"]');
if ($select) {
$selects.hide();
$select.show();
$tabs.removeClass('active');
$tab.addClass('active');
}
}, reset: function () {
this.$element.val(null).trigger('change');
}, destroy: function () {
this.unbind();
this.$element.removeData(NAMESPACE).removeClass('city-picker-input');
this.$textspan.remove();
this.$dropdown.remove();
},
//远程加载数据
remoteLoadData: function (cityType,cityId) {
706 var resultData = {};
707 if(PROVINCE===cityType)
708 {
709 return ChineseDistricts[cityId];
710 }
711 $.ajax({
712 url: "/directoryProcurement/jd/cityData/"+cityType+"/"+cityId,
713 type: "GET",
714 dataType: "json",
715 async: false,
716 contentType: "application/json",
717 success: function (result) {
718 if(result.code=="0")
719 {
720 resultData = result.data;
721 }else
722 {
723 console.log(result.desc);
724 }
725 }
726 });
727 return resultData;
728 }
}; CityPicker.DEFAULTS = {
simple: false,
responsive: false,
placeholder: '请选择省/市/区/镇',
level: 'county',
province: '',
city: '',
district: '',
county:''
}; CityPicker.setDefaults = function (options) {
$.extend(CityPicker.DEFAULTS, options);
}; // Save the other citypicker
CityPicker.other = $.fn.citypicker; // Register as jQuery plugin
$.fn.citypicker = function (option) {
var args = [].slice.call(arguments, 1); return this.each(function () {
var $this = $(this);
var data = $this.data(NAMESPACE);
var options;
var fn; if (!data) {
if (/destroy/.test(option)) {
return;
} options = $.extend({}, $this.data(), $.isPlainObject(option) && option);
$this.data(NAMESPACE, (data = new CityPicker(this, options)));
} if (typeof option === 'string' && $.isFunction(fn = data[option])) {
fn.apply(data, args);
}
});
}; $.fn.citypicker.Constructor = CityPicker;
$.fn.citypicker.setDefaults = CityPicker.setDefaults; // No conflict
$.fn.citypicker.noConflict = function () {
$.fn.citypicker = CityPicker.other;
return this;
}; $(function () {
$('[data-toggle="city-picker"]').citypicker();
});
});
上面的代码的第一个红色字体处,是为将省和直辖市这种一级地址默认加载过来,其他的三级地址都是靠远程加载过来,
第二处红色字体是为了解决,上面是为了解决一个bug,就当选择了,一级二级三级和四级地址后,如果再重新选择一级地址,后面的三级地址不会清空重选,这样会造成地址归属地不对的问题,这个bug在city-picker原生的代码中是没有的,应该是上面那个博客里,改成四级地址后才出现的bug。
第三处红色字体是为了判断是否有应该去进行远程加载数据,如果只选择了一级地址,就不去远程加载数据,反之则调用远程加载数据方法。
第四处红色字体,是关键了,实现远程加载数据的方法,这个方法是我自己后来加的,写成了同步请求。因为有些地址就没有三级地址,例如北京、丰台、三环到四环之间、这就是一个完整的选择地址了,所以会把一些没有四级地址的信息打印出来,如果有需要的可以修改这个远程加载数据的方法,来实现自己的需求。
最后忘记说了,我是将city-picker.js这个插件的city-picker.data.js和city-picker.js这两个文件合并成了一个文件,因为我只需要默认加载一级地址,一级地址的内容也不多,就写在了一起了,就是第一处红色字体处的js全局对象。
粗略的改造,接受批评。