如何在 JavaScript/jQuery 中创建动态 SELECT 下拉列表?

5 html javascript jquery

我想在组合框中显示部门表中的所有部门名称。我有一个函数可以获取所有部门名称。如何使用 javaScript 或 jQuery 在运行时动态创建组合框。

代码

     <select id="searchDepartments">
     </select> <input type="button" value="Search" onClick="search();" />
Run Code Online (Sandbox Code Playgroud)

JavaScript 函数

function getDepartments(){
EmployeeManagement.getDeptList(function(deptList/*contains n-(dept.id, dept.name)*/{
    for(i = 0; i<deptList.length; i++){
Run Code Online (Sandbox Code Playgroud)

我怎样才能编写生成(添加)选项到列表的代码?

lin*_*lnk 6

该过程是为option列表中的每个项目创建一个节点,并将其添加为select元素的子元素。

在普通的javascript中:

var sel = document.getElementById('searchDepartments');
var opt = null;

for(i = 0; i<deptList.length; i++) { 

    opt = document.createElement('option');
    opt.value = deptList[i].id;
    opt.innerHTML = deptList[i].name;
    sel.appendChild(opt);
}
Run Code Online (Sandbox Code Playgroud)