我的数据库中有两个表。一个是部门,另一个是经理。我在JSP中创建了一个下拉列表,它显示了来自数据库的Departments列表。我想根据所选部门显示另一个下拉列表中的经理列表。怎么实现这个?
这里,我指的是级联下拉列表。谢谢你。
答案 0 :(得分:1)
您没有提供任何HTML或您尝试过的任何脚本,因此以下内容应该是您开始使用的好模板。
假设以下HTML
<div>
<div style="float: left;">
Select Department
<br />
<select id="departments"></select>
</div>
<div style="float: left; margin-left: 10px;">
Select Manager
<br />
<select id="managers"></select>
</div>
</div>
从数据库加载部门和管理器后,可以使用与此类似的代码动态填充选择:
var $departments = $("#departments");
var $managers = $("#managers");
// This data would be loaded from the DB
var departments = [
{id: "1", value: "Department 1"},
{id: "2", value: "Department 2"}
];
// This data would be loaded from the DB
var managers = [
{ departmentId: "1", value: "Dep 1 Manager 1"},
{ departmentId: "1", value: "Dep 1 Manager 2"},
{ departmentId: "1", value: "Dep 1 Manager 3"},
{ departmentId: "1", value: "Dep 1 Manager 4"},
{ departmentId: "1", value: "Dep 1 Manager 5"},
{ departmentId: "1", value: "Dep 1 Manager 6"},
{ departmentId: "1", value: "Dep 1 Manager 7"},
{ departmentId: "1", value: "Dep 1 Manager 8"},
{ departmentId: "1", value: "Dep 1 Manager 9"},
{ departmentId: "1", value: "Dep 1 Manager 10"},
{ departmentId: "2", value: "Dep 2 Manager 1"},
{ departmentId: "2", value: "Dep 2 Manager 2"},
{ departmentId: "2", value: "Dep 2 Manager 3"},
{ departmentId: "2", value: "Dep 2 Manager 4"},
{ departmentId: "2", value: "Dep 2 Manager 5"},
{ departmentId: "2", value: "Dep 2 Manager 6"},
{ departmentId: "2", value: "Dep 2 Manager 7"},
{ departmentId: "2", value: "Dep 2 Manager 8"},
{ departmentId: "2", value: "Dep 2 Manager 9"},
{ departmentId: "2", value: "Dep 2 Manager 10"}
];
function getManagers() {
$managers.empty();
var departmentId = $departments.val();
for (i = 0; i < managers.length; i++) {
if (managers[i].departmentId === departmentId) {
$managers.append("<option value='" + managers[i].departmentId + "'>" + managers[i].value + "</option>");
}
}
}
for (i = 0; i < departments.length; i++) {
$departments.append("<option value='" + departments[i].id + "'>" + departments[i].value + "</option>");
}
getManagers();
$departments.on("change", function(){
getManagers();
});
我已经对部门和经理来源进行了硬编码,因为我没有数据库。