经常需要用到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 }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-20
  • 2021-07-15
  • 2022-01-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-01
  • 2022-12-23
  • 2021-10-02
  • 2022-12-23
  • 2021-09-21
  • 2022-12-23
相关资源
相似解决方案