项目场景:
考试系统中为考试试卷设置考试题目,下次进来设置时显示上次选中的试题
问题描述:
数据传输问题,后台需要传给前端查询到所有试题id的list,传list不方便获取,就用了LinkedHashMap
//获取当前试卷选中的试题id
List <String> questionIds = questionCreateService.getAllQuestions(id);
Map<Integer, String> json = new LinkedHashMap<Integer, String>();//使用LinkedHashMap保证顺序
for (int i = 0; i < questionIds.size(); i++) {
json.put(i, questionIds.get(i));
}
model.addAttribute("questionIds",json);
前端接收
前端html接收时用了一个下拉框将所有的试题id进行接收,并隐藏
<div class="col-sm-8" style="display:none;" >
<select name="typeId" id="typeId" class="form-control" >
<option th:each="type:${questionIds}" th:value="${type.key}" th:text="${type.value}" ></option>
</select>
</div>
js设置选中
在checkbox中添加改变状态
columns : [
{
checkbox : true,
formatter : stateFormatter
},
在下面设置回显
//控制上次选中的回显
function stateFormatter(value, row, index) {
var obj = document.getElementById('typeId');
var options = obj.options;
for(var i=0,len=options.length;i<len;i++){
var opt = options[i];
if ( opt.text == row.id){
return {
//disabled : false,//设置是否可用
checked : true//设置选中
};
}
}
return value;
}