1.先定义页面需要监听展现的元素 name="courseTemplate.levelId" class="state"
<div class="layui-input-inline">
<select name="courseTemplate.levelId" class="state">
<option value="">请选教育程度</option>
</select>
</div>
<div class="layui-input-inline">
<select name="courseTemplate.gradeId" class="state" >
<option value="">请选授课年级</option>
</select>
</div>
<div class="layui-input-inline">
<select name="courseTemplate.subjectId" class="state">
<option value="">请选授课科目</option>
</select>
</div>
2. javascipt
layui.use(['layer', 'jquery', 'form'], function () {
var layer = layui.layer,
$ = layui.jquery,
form = layui.form;
var url = "${base}/course/courseTemplate/Com_JsonBaseEduGrade.do"; //数据请求地址
var level = "";
var grade = "";
var subject = "";
getJSON(url + "?treeType=1", $("select[name='courseTemplate.levelId']").closest("div")); //初始化第一个元素
var type;
form.on('select(state)', function (data) { //进行监听 看元素是否变化,获取下一个下拉框数据
$that = $(data.elem);
type = data.elem.name;
var urls = "";
if (type == "courseTemplate.levelId") {
urls = url + "?treeType=2&levelId=" + data.value;
} else
if (type == "courseTemplate.gradeId") {
var levelId = $("select[name='courseTemplate.levelId']").val();
urls = url + "?treeType=3&levelId=" + levelId + "&gradeId=" + data.value;
}
getJSON(urls, $that.closest("div").next());
});
function getJSON(urls, even) {
$.getJSON(urls, function (json) {
var pid = 0;
var name = even.find("select").attr("name");
var select = "<select name=\"" + name + "\" lay-filter=\"state\">";
select += "<option value=\"0\">请选择 </option>";
$(json).each(function () {
select += "<option value=\"" + this.id + "\"";
if (level == this.nameCn || grade == this.nameCn || subject == this.nameCn) {
select += " selected=\"selected\" ";
pid = this.id;
}
select += ">" + this.nameCn + "</option>";
});
select += "</select>";
even.html(select);
var nextName = even.next().find("select").attr("name");
even.next().html("<select name=\"" + nextName + "\" lay-filter=\"state\"><option value=\"0\">请选择 </option></select>");
form.render('select');
if (pid != 0) {
var urls = "";
if (name == "courseTemplate.levelId") {
urls = url + "?treeType=2&levelId=" + pid;
} else if (name == "courseTemplate.gradeId") {
var levelId = $("select[name='courseTemplate.levelId']").val();
urls = url + "?treeType=3&levelId=" + levelId + "&gradeId=" + pid;
}
getJSON(urls, even.next());
}
});
}
});