/** * LinkedSelect: 联动下拉框控件,支持N级联动。 * 根据每个Select的定义中的url和id为Select做初始化,后台返回的数据为[{value:"",label:""},{value:"",label:""}]形式的数组json * @author senton * @version 1.0 * * 以选国家、省、市的联动为例,调用示例如下: *
 *  // 声明一个select变量
 * 	var select = new LinkedSelect();
 *  // 调用selct的init()方法,注意,该方法的参数是一个数组,用[]括起来,每个select的定义用{}括起来,多个select定义之间以,分割
 * 	select.init([
 * 		{
 * 			id:"country",
 * 			url:"获取country列表的url",
 * 			nullable:false,
 * 			defaultValue:2
 * 		},
 * 		{
 * 			id:"province",
 * 			url:"获取province列表的url",
 * 			nullable:false
 * 		},
 * 		{
 * 			id:"city",
 * 			url:"获取city列表的url",
 * 			nullable:false
 * 		}
 *  ]); 
 * 
*/ /** * 定义一个LinkedSelect函数 */ function LinkedSelectValues(){ return this; } /** * LinkedSelect的初始化方法 * @param allSelectInputs 所有的需要联动显示的下拉框,是一个数组。 * @returns */ LinkedSelectValues.prototype.init = function(allSelectInputs){ // 定义一个内部方法,用于加载一个下拉框,参数: // allSelectInputs:所有的下拉框定义 // parentId: 上一个被选中的ID,即"); _initNextSelect(allSelectInputs, jQuery("#"+currentSelect.id).val(), currentIndex + 1); return; } } // 如果不为空,则根据parentId取出所有的SelectItem初始化currentSelect $.ajax({url:currentSelect.url, data:{ parentId:parentId }, beforeSend: function (xhr) { //设置请求头 //xhr.setRequestHeader("User-Agent", "headertest"); //console.log(JSON.stringify(sysComm)); xhr.setRequestHeader("x-auth-token", fn.getToken()); }, success: function(data){ if(data != null && data !="" && data !=undefined){ jQuery("#"+currentSelect.id).empty(); // 如果currentSelect在被定义时nullable为true,则说明可以为空,在第一个加上一个空的option if(currentSelect.nullable){ jQuery("#"+currentSelect.id).append(""); } // 取出所有的selectItem加到currentSelect上 jQuery.each(data, function (index, selectItem) { // 如果currentSelect在被定义时的defaultValue等于当前selectItem的值,则选中它 if(selectItem.value == currentSelect.defaultValue){ if(selectItem.userDefined !== null){//weizy 添加对新添属性的控制 jQuery("#"+currentSelect.id).append(""); }else{ jQuery("#"+currentSelect.id).append(""); } }else { if(selectItem.userDefined !== null){ jQuery("#"+currentSelect.id).append(""); }else{ jQuery("#"+currentSelect.id).append(""); } } }); $("#"+currentSelect.id).selectpicker('refresh'); // 初始化完毕后,取出当前currentSelect选中的值,作为parentId初始化下一个select _initNextSelect(allSelectInputs, jQuery("#"+currentSelect.id).val(), currentIndex+1); }else{ console.log("下拉框加载失败") } } }); }; // 调用_initNextSelect,启动第一个下拉框的加载 _initNextSelect(allSelectInputs, "", 0); };