1.for循环闭包问题
adc-da1.2 用户管理模块,新增功能需要根据T_S_DictionaryType数据库自动在下拉列表生成option
性别(dictionaryCode:SEX),状态( dictionaryCode : STATE )下拉框都是在for循环动态生成的,每次将对应的dictionaryCode传到getDropDownlist()获取下拉框的option
原代码:
1 for(var i=0 ;i<rowCount; i ++){ 2 if(header[i].isShow=="是"){ 3 dynamicHeader = dynamicHeader+"<th>"+header[i].content+"</th>"; 4 } 5 var htmlStr = '<div class="form-group">'+'<label for="'+header[i].fieldName+'" class="col-sm-2 control-label">'+header[i].content+':</label>'+ 6 '<div class="col-sm-7">'+'<input type="text" class="form-control" id="'+header[i].fieldName+'" name="'+header[i].fieldName+'" placeholder="'+header[i].content+'"></div></div>'; 7 if(header[i].showType == "dropdownlist"){ 8 htmlStr = '<div class="form-group">'+'<label for="'+header[i].fieldName+'" class="col-sm-2 control-label">'+header[i].content+':</label>'+ 9 '<div class="col-sm-7">'+'<select class="form-control" id="'+header[i].fieldName+'" name="'+header[i].fieldName+'" data-placeholder="'+header[i].content+'"><option></option></select></div></div>'; 10 11 dictionaryCode = header[i].fieldName; 12 console.log("----------"+dictionaryCode+"---------"); 13 //下拉框 14 15 setTimeout(function(){ 16 $("#"+dictionaryCode).select2({ 17 ajax:getDropDownList(dictionaryCode) //getDropDownList(header[i].fieldName) 18 }); 19 },100); 20 21 }
1 function getDropDownList(dictionaryCode){ 2 console.log("@@@@"+dictionaryCode); 3 var rurl= addr+"/api/sys/dictionary/page";//?pageNo=1&pageSize=8&dictionaryCode="+dictionaryCode; 4 var list = { 5 url: rurl, //+dictionaryCode, 6 delay: 250, 7 allowClear: true, 8 data:{ 9 pageNo:pageNo, 10 pageSize:pageSize, 11 dictionaryCode:dictionaryCode, 12 dictionaryName:"" 13 }, 14 placeholder: { 15 id: '-1', // the value of the option 16 text: '请选择1' 17 }, 18 processResults: function (data) { 19 console.log("---xxxx----"+data); 20 var cur = data.data.list[0].dicTypeEOList, 21 selectrole = [{"id":" ", "text":"---请选择---"}]; 22 // alert(JSON.stringify(data.data.list[0])); 23 for (var i =0;i<cur.length;i++){ 24 var land = cur[i]; 25 var option = {"id":land.dicTypeName, "text": land.dicTypeName}; 26 selectrole.push(option); 27 } 28 console.log(selectrole); 29 return { 30 results: selectrole 31 }; 32 }, 33 templateResult: function (data) { 34 if (data.id == '') { // adjust for custom placeholder values 35 return '请选择'; 36 } 37 return data.text; 38 }, 39 cache:true, 40 success:function(){ 41 console.log(arguments) 42 } 43 }; 44 console.log(list); 45 return list; 46 }
但是后台打印信息为
这里是执行完for循环再去执行两次getDropDownList()函数,传入的两次参数都是STATE造成错误,这是JS for循环的闭包问题
https://www.cnblogs.com/ZinCode/p/5551907.html
修改后: