一、项目场景
一个后台管理系统,一个业务系统,在后台管理系统中配置某一个页面的各种数据数据方式,例如下拉框、单选框、输入框等,然后业务系统读取对应的配置,渲染页面
二、页面渲染
1、代码
<div id="showExpandInfo">
<table id="showData">
<tr th:each="item:${config}">
<td width="200" th:text="${item.expandName}"></td>
<!--<td colspan="2"><span th:text="${item.value}"></span></td>-->
<td colspan="2"><span th:id="${item.expandName}"></span></td>
</tr>
</table>
<table id="updateData" hidden>
<tr th:each="item:${config}">
<!--<td width="22">-->
<!--<em class="icon28" style="margin-right:5px;"></em></td>-->
<td width="200" th:text="${item.expandName}"></td>
<td colspan="2" th:if="${item.expandType}=='select'">
<select>
<option th:each="selectValues:${item.valueScopeArray}" th:id="${item.expandName}+1" th:text="${selectValues.v}" th:value="${selectValues.v}"></option>
</select>
</td>
<td th:if="${item.expandType}=='checkRadio'">
<input th:id="${item.expandName}+1" th:each="testValue:${item.valueScopeArray}" type="radio" th:name="${item.expandName}" th:text="${testValue.v}" th:value="${testValue.v}">
</td>
<td colspan="2" th:if="${item.expandType}=='input'">
<input th:id="${item.expandName}+1" type="text" class="text" th:placeholder="请输入您的+${item.expandName}">
</td>
<!--<td colspan="2" th:if="${item.expandType}!='select'" th:each="testValue:${item.valueScopeArray}">-->
<!--<input th:type="${item.expandType}" th:text="${testValue.name}"/>-->
<!--</td>-->
</tr>
</table>
</div>
2、th表达式详解
th:each循环遍历数据,格式为th:each="item:${config}(th:each="索引:集合)
th:text渲染显示文本
th:value实际获取的值,常用作传参
th:id作为标签id,由于是动态的,在js中根据id获取值时,需要先查询所有的id的变量值,作为一个集合循环取值
对于单选框数据,我这里采用了如下的处理方式,由于id是重复的,所以采用获取元素去判断是否选中,只拿选中的值,这里的单选框判断也是通过后端返回数据,对应某些id为单选框去处理
for(var index in ids){
if(ids[index].substr(0,1)=='*'){
//单选框类型的数据
var name = ids[index].substring(1,ids[index].length);
var value = "";
var elements = document.getElementsByName(name.substring(0,name.length-1));
for(var i=0;i<elements.length;i++){
if(elements[i].checked){
value = elements[i].value;
}
}
result = name+","+value;
}else{
var name = ids[index];
var value = $("#"+name).val();
result = name+","+value;
}
extendInfo+=result+";";
}
for(var index in ids){
if(ids[index].substr(0,1)=='*'){
//单选框类型的数据,默认选中第一个
var name = ids[index].substring(1,ids[index].length-1)
document.getElementsByName(name)[0].checked=true
}
}