在开发web应用时,经常遇到类似省市区级联下拉框操作,即选中省份自动级联加载该省份所有的市,选中市自动级联加载该市所有的区;假设省市区的数据量很大,此时用户想选中某市,因而要从上往下查找,可能半天都找不到,用户体验不佳,因此引入jQuery插件–自动补齐flexselect可解决该弊端,因为该插件支持模糊检索自动补齐,可在极短时间内找到想要的结果,节省了时间又增强了用户操作速度。
自动补齐flexselect插件用法请看:http://www.tieguanyin168.com/index.php/jqueryflexselect-1505.html
以下模拟省市区级联案例,效果如下:
源码:
1、服务器端代码
public void queryCity() { String grade=this.getParameter("grade"); List<City> models = cityService.searchCitiesByPid(Integer.valueOf(grade)); if(models!=null&&models.size()>0){ //{"code":200,"data":[{"acronym":"LCQ","areaCode":"","fullName":"福建省泉州市鲤城区","grade":3,"id":1463,"isDel":0,"name":"鲤城区","pid":162,"sellQuantity":0,"signQuantity":0,"zipCode":""}, // {"acronym":"NAS","areaCode":"","fullName":"福建省泉州市南安市","grade":3,"id":1474,"isDel":0,"name":"南安市","pid":162,"sellQuantity":0,"signQuantity":0,"zipCode":""}], // "success":true} Utils.returnJson(models); } }
2、jsp代码
<div class="bg_row_out"> <div class="bg_row_out_1"> <font color="red">*</font>省:</div> <div class="bg_row_out_2 required" style="border-right: 0 none;border-bottom: 0px solid #cccccc;"> <!--从服务器获取--> <select id="provice" name="company.provice" class="newsletter_input"> <option value=""></option> <c:forEach items="${provinces}" var="provice"> <option value="${provice.id }">${provice.name }</option> </c:forEach> </select> </div> </div> <div class="bg_row_out"> <div class="bg_row_out_1"> <font color="red">*</font>市:</div> <div class="bg_row_out_2 required" style="border-right: 0 none;border-bottom: 0px solid #cccccc;"> <select id="city" name="company.city" class="newsletter_input"> <option value=""></option> </select> </div> </div> <div class="bg_row_out"> <div class="bg_row_out_1"> <font color="red">*</font>区:</div> <div class="bg_row_out_2 required" style="border-right: 0 none;border-bottom: 0px solid #cccccc;"> <select id="district" name="company.district" class="newsletter_input"> <option value=""></option> </select> </div> </div>
3、js代码
$(function(){ var district = $("#district").flexselect(); $("#provice").flexselect({callback:function(){ $.ajax( { url : "queryCity.htm", data : { "date" : new Date().getTime(), "grade" : $("#provice").val() }, dataType:"json", success : function(result) { if(result.code != 200){ alert(result.data); return; } result = result.data; var resultStr = []; for ( var i = 0; i < result.length; i++) { resultStr.push({name:result[i].name, value:result[i].id}); } city.flexselect[0].cache = resultStr; } }) } }); var city=$("#city").flexselect({callback:function(){ $.ajax( { url : "queryCity.htm", data : { "date" : new Date().getTime(), "grade" : $("#city").val() }, dataType:"json", success : function(result) { if(result.code != 200){ alert(result.data); return; } result = result.data; var resultStr = []; for ( var i = 0; i < result.length; i++) { resultStr.push({name:result[i].name, value:result[i].id}); } district.flexselect[0].cache = resultStr; } }) } }); });