基於jquery實現html
jsjquery
var selectCon = [ {"id" : "#countryID","name" : "國家"}, {"id" : "#provinceID","name" : "省份"}, {"id" : "#cityID","name" : "城市"}, {"id" : "#countyID","name" : "地區"} ]; /** 移除所有選擇項內容,並添加默認提示信息,參數selectCon的下標*/ function removeOption() { var id = ""; var option = ""; for ( var i = 0; i < arguments.length; i++) { id = selectCon[arguments[i]].id; option = id + " option"; $(option).remove(); $(id).append( "<option value=''>請選擇" + selectCon[arguments[i]].name + "</option>"); } }; /** 追加選擇項內容,參數:要添加的jqueryId,行政區域父id*/ function addOption(jqueryId, parentId) { if (!parentId) { return; } var url = "${pageContext.request.contextPath}/district/getDistricte.do"; $.post(url, { "parentId" : parentId }, function(jsonString) { var size = jsonString.length; var option = ""; for ( var i = 0; i < size; i++) { option += "<option value='"+jsonString[i].id+"'>" + jsonString[i].name + "</option>"; } $(jqueryId).append(option); //console.log(option); }); }; //國家-省 $("#countryID").change(function() { var parentId = $("#countryID option:selected").val(); removeOption(1, 2, 3); addOption("#provinceID", parentId); }); //省份-城市 $("#provinceID").change(function() { var parentId = $("#provinceID option:selected").val(); removeOption(2, 3); addOption("#cityID", parentId); }); //城市-區域 $("#cityID").change(function() { var parentId = $("#cityID option:selected").val(); removeOption(3); addOption("#countyID", parentId); });
html產品可見地區: <select id="countryID"> <option value="">請選擇國家</option> <option value="1">中國</option> </select> <select id="provinceID"><option value="">請選擇省份</option></select> <select id="cityID"><option value="">請選擇城市</option></select> <select id="countyID"><option value="">請選擇地區</option></select>
返回的格式示例:
sql
[ { "id": 3, "parentId": 2, "code": "110100", "name": "北京市轄區" }, { "id": 18, "parentId": 2, "code": "110200", "name": "\n縣" } ]
CREATE TABLE `tb_district` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_id` int(11) DEFAULT NULL, COMMENT '父id' `code` varchar(6) NOT NULL DEFAULT '' COMMENT '行政編碼', `name` varchar(255) NOT NULL DEFAULT '' COMMENT '行政名稱', PRIMARY KEY (`id`), UNIQUE KEY `uni_district_code` (`code`), KEY `parent_id` (`parent_id`), ) ENGINE=InnoDB AUTO_INCREMENT=3515 DEFAULT CHARSET=utf8 COMMENT='行政編碼表';