思路
手动拼接option,然后使用form.render()重新渲染。加载数据前禁用select并显示“加载中...”,加载完成(异步)后取消禁用select,并重新渲染。
代码
showAddLayer();
// 显示添加用户弹出层
function showAddLayer() {
resetForm("#form-add-user");
loadUnitList();// 加载单位select
loadRoleList();// 加载角色select
// 添加用户弹出层配置
layui.use('layer', function() {
layer.open({
type : 1,
title : '添加用户',
shadeClose : false, //点击遮罩关闭层
//area : [ '50%', '80%' ],//弹出层大小
area : '678px',//只定义宽度
content : $('#layer-add-user'),
//btn : "关闭",
anim : 0,
resize : false
});
});
}
// 加载所有单位列表(学院、职能部门、其他)
function loadUnitList() {
var departmentList = [];
var collegeList = [];
//加载部门列表
$.ajax({
url : "department/all",
beforeSend : function() {
// 禁用下拉框并显示加载中
$("#form-add-user select[name=unitId]").attr("disabled", "disabled");
$("#form-add-user select[name=unitId] option:first").html("加载中...");
},
success : function(res) {
departmentList = res.data.listDepartment;
// 加载学院列表
$.ajax({
url : "college/all",
success : function(res) {
collegeList = res.data.listColleges;
createOptions(departmentList, collegeList);
},
error : function(res) {
console.log(res);
},
complete : function() {
$("#form-add-user select[name=unitId]").removeAttr("disabled");
$("#form-add-user select[name=unitId] option:first").html("");
// 重新渲染select
layui.use("form", function() {
var form = layui.form;
form.render("select");
});
}
});
},
error : function(res) {
console.log(res);
},
});
}
// 拼接option
function createOptions(departmentList, collegeList) {
var options = "";
var $unit = $("#form-add-user select[name=unitId]");
$unit.empty();// 清空子节点
// 拼接options
options += '<option value="">请选择</option>';
options += '<optgroup label="职能部门">';
for ( var index in departmentList) {
options += '<option value="2-'+departmentList[index].id+'">' + departmentList[index].name + '</option>';
}
options += '</optgroup>';
options += '<optgroup label="学院">';
for ( var index in collegeList) {
options += '<option value="1-'+collegeList[index].id+'">' + collegeList[index].name + '</option>';
}
options += '</optgroup>';
options += '<optgroup label="其他">';
options += '<option value="3">其他(可在备注写明)</option>';
options += '</optgroup>';
// 将options添加到dom树中
$unit.append(options);
}
//加载所有角色列表
function loadRoleList() {
var mData = [];
$.ajax({
url : "role/all",
beforeSend : function() {
// 禁用下拉框并显示加载中
$("#form-add-user select[name=roleIds]").attr("disabled", "disabled");
$("#form-add-user select[name=roleIds] > option").html("加载中...");
},
success : function(res) {
sort(0, res.data.listRole);
// 加载角色下拉框数据
layui.use("formSelects", function() {
var formSelects = layui.formSelects;
formSelects.data("select-roleIds", "local", {
arr : mData
});
});
},
error : function(res) {
console.log(res);
},
complete : function() {
// 取消禁用下拉框
$("#form-add-user select[name=roleIds]").removeAttr("disabled");
$("#form-add-user select[name=roleIds] > option").html("");
}
});
效果
将谷歌浏览器【network】调成【slow 3G】查看效果