项目中经常用到Select标签,用封装好的方法获取option,可以避免冗赘的代码;
1.JSP--标签
<select class="width_md" name="queryProjectSupType" id="queryProjectSupType" title="项目类型-大类"></select>
2.JS1--实例化option
<script type="text/javascript"> $().ready(function(){ SELECT_LIST.getProjectSupType("queryProjectSupType", "${pd.queryProjectSupType}");
}) </script>
3.JS2--数据封装
var SELECT_LIST = { getProjectSupType: function(targetId,selectValue){ var url = 'dictionary/list/condition'; var dicType = {}; dicType.url = url;//ajax的url dicType.targetId = targetId;//即将实例化的select标签的id dicType.keyValue = "dicName";//从数据库获取的Json数据,将key为"dicName"的value赋值给option的value属性 dicType.keyName = "dicName";//从数据库获取的Json数据,将key为"dicName"的value赋值给option的text属性 dicType.condition = {codeId:8};//这是从传给数据库的数据筛选条件,因需求而异 dicType.firstOption = "<option value=''>请选择分类</option>";//默认的第一个option标签的text属性 dicType.selectedValue = selectValue;//标签实例化后,value等于selectValue的option,将默认选中 ajaxGenerateSelect(dicType);//ajax获取数据,生成option数据 } }
3.JS3--1.ajax获取数据,2.js生成option标签,并放入Select标签
function ajaxGenerateSelect(selectObject){ var url = selectObject.url; var method = selectObject.method ? selectObject.method : "POST"; var keyValue = selectObject.keyValue ? selectObject.keyValue : "id"; var keyName = selectObject.keyName ? selectObject.keyName : "name"; var selectedValue = selectObject.selectedValue ? selectObject.selectedValue : null; var targetId = selectObject.targetId; var condition = selectObject.condition ? selectObject.condition : {}; var afterHandle = selectObject.afterHandle; var formatter = selectObject.formatter; var firstOption = selectObject.firstOption; var ajaxObject = {}; ajaxObject.url = url; ajaxObject.method = method; ajaxObject.data = JSON.stringify(condition); ajaxObject.success = function(result){ var data = result.data; var html = ""; if(firstOption){ html = firstOption; } for(var i=0;i<data.length;i++){ var selected = ""; var dataItem = data[i]; if(selectedValue == dataItem[keyValue]){ selected = "selected"; } var option = "<option value='#(value)' #(selected)>#(name)</option>"; var nameValue = dataItem[keyName]; if(formatter){ nameValue = formatter(dataItem); } option = option.replace("#(value)", dataItem[keyValue]). replace("#(name)",nameValue).replace("#(selected)", selected); html += option; } $("#" + targetId).html('').append(html); if(afterHandle){ afterHandle(); } }; ajaxMethod(ajaxObject); }