我的数据库中有两个表。一个是部门,另一个是经理。我在 JSP 中创建了一个下拉列表,它显示了数据库中的部门列表。我想根据所选部门在另一个下拉列表中显示经理列表。如何做到这一点?
在这里,我指的是级联下拉菜单。谢谢。
我的数据库中有两个表。一个是部门,另一个是经理。我在 JSP 中创建了一个下拉列表,它显示了数据库中的部门列表。我想根据所选部门在另一个下拉列表中显示经理列表。如何做到这一点?
在这里,我指的是级联下拉菜单。谢谢。
您没有提供任何 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();
});
因为我没有数据库,所以我对部门和经理的来源进行了硬编码。