Js异步级联选择框实践方法
HTML:
<li> <span>所在地区:</span> <select name="prov" id="ddl_prov" onchange="event_change_prov(this);" class="required" missingmsg="请选择省"> <option value="">请选择省</option> </select> </li> <li> <span></span> <select name="city" id="ddl_city" onchange="event_change_city(this);" class="required" missingmsg="请选择市"> <option value="">请选择市</option> </select> </li> <li> <span></span> <select name="area" id="ddl_area" class="required" missingmsg="请选择区"> <option value="">请选择区</option> </select> </li>
Javascript:
//省值改变 function event_change_prov(self) { var value = $(self).val(); if (isEmpty(value)) { bindDropdownList("ddl_city", []) } else { bindArea("ddl_city", value); } } //市值改变 function event_change_city(self) { var value = $(self).val(); if (isEmpty(value)) { bindDropdownList("ddl_area", []) } else { bindArea("ddl_area", value); } } //绑定下拉框 function bindDropdownList(targetId, data) { $("#" + targetId).html(""); var html = ""; if (targetId == "ddl_prov") { html="<option value=''>请选择省</option>"; } else if (targetId == "ddl_city") { html = "<option value=''>请选择市</option>"; } else if (targetId == "ddl_area") { html = "<option value=''>请选择区</option>"; } else { html = "<option value=''>请选择</option>"; } for (var i = 0; i < data.length; i++) { html = html + "<option value='" + data[i].Value + "'>" + data[i].Text + "</option>"; } $("#" + targetId).html(html); } //级联下拉框列表 var ddls = ["ddl_prov", "ddl_city", "ddl_area"]; //绑定地区 function bindArea(id, code) { if (isEmpty(id) || $("#" + id).length == 0) {return; } if (id == "ddl_prov" && isEmpty(code)) { code = ""; } Request.get('/XXX/XXX?code=' + code, function (result) { bindDropdownList(id, result); var name = $("#" + id).attr("name"); var or = $("#hid_" + name).val(); if (isEmpty(or)) {return; } $("#" + id).val(or); var ncode = $("#" + id).val(); var index = ddls.indexOf(id); if (index >= 0 && index < ddls.length - 1) { var nid = ddls[index + 1]; bindArea(nid, ncode); } }); }