js动态生成下拉列表

经常需要用到js动态生成下拉列表的功能,记录下来备用。

示例需求:通过ajax请求,从后台获取用户姓名列表,并添加到下拉列表中。js代码如下:

 1 function getNameList(){
 2 //如果是类似三级联表的功能,则需在刚开始是对下拉列表进行初始化,如:
 3     $("#nameList").html("<option value='0'>请选择姓名</option>");
 4     $.getJSON(url+"getNameList",{},function(result){
 5         if(result.errcode == 0){
 6             var jsonNameList = eval(result.data.list);
 7             
 8             if(jsonNameList==""){
 9                 $("#nameList").html("<option value='0'>没有数据</option>");//如果没有数据,则把下拉列表的第一条记录显示为“没有数据”
10             }else{
11                 //循环,把名字append到namaList列表上
12                 for(var i=0;i<jsonNameList.length;i++){
13                     var o = document.createElement("option");
14                     o.value = jsonNameList[i].Id;
15                     o.text = jsonNameList[i].name;
16                     $("#nameList").append(o);
17                 }    
18             }
19         }else {
20             alert(result.info);
21         }
22     });
23 }
原文地址:https://www.cnblogs.com/iyitong/p/4251529.html