某同事,遇到LayUI的中下拉框回显数据问题,在这里记录一下,回显数据解决方式:
- 通过模版引擎进行比较设置selected属性
- 通过JavaScript设置select标签的值,设置回显
本次案例使用的Thymeleaf模板下的layui下选框回显,动态生成的HTML页面结果:
<div class="layui-form-item">
<label class="layui-form-label"><span class="color-red">* </span>发送对象:</label>
<div class="layui-input-inline">
<select id="bookList">
<option value="">请选择</option>
<option value="1">西游记</option>
<option value="2">红楼梦</option>
<option value="3">水浒传</option>
<option value="4">三国演义</option>
</select>
</div>
</div>
1.标签方式
//控制器传递的数据代码
model.addAttribute("bookId",3);
model.addAttribute("bookList",bookList);
(1)下拉框的单选回显
<div class="layui-form-item">
<label class="layui-form-label"><span class="color-red">* </span>发送对象:</label>
<div class="layui-input-inline">
<select id="bookList">
<option value="">请选择书籍</option>
<option th:each="book:${bookList}" th:text="${book['name']}" th:value="${book['id']}"
th:selected="${book['id'] eq bookId}"
></option>
</select>
</div>
</div>
(2)单选框的单选回显
<input type="radio" name="bookRadio" th:each="book:${bookList}" th:text="${book['name']}" th:value="${book['id']}" th:checked="${book['id'] eq bookId}">
(3)复选框的多选回显(扩展)
model.addAttribute("arr",new int[]{2,3});
<input type="checkbox" name="bookCheckBox" th:each="book:${bookList}" th:text="${bookList['name']}" th:value="${bookList['id']}" th:checked="${#arrays.contains(arr,hobby['id'])}">
上述的方式:都是通过自带的标签进行控制
2.JavaScript方式
在没有遇到LayUI的时候,我可以轻松搞定,代码如下:
<select id="bookList">
<option value="">请选择爱好</option>
<option th:each="book:${bookList}" th:text="${book['name']}" th:value="${book['id']}"></option>
</select>
<script>
let bookId = '[[${bookId}]]';
document.getElementById("bookList").value=bookId;
</script>
注意:当引入LayUI的时候,上述通过JavaScript设置回显的方式==失效==,因为当使用LayUI渲染后的结构如下
这里就说坑不坑吧?通过代码分析我们也知道为什么无法回显数据了吧?此处select可供选择的元素是通过jquery从后台数据获得的,需要根据动态结果决定选择哪一个。分析一下渲染结果的结构,得到dom树如下:
发现在layui-input-inline之下除了select之外又多了个layui-form-select的div。该div包含layui-select-title和dl两个孩子元素,select的选择事件可以通过点击dl下某个确定的dd元素实现。
let bookId = '[[${bookId}]]';
if(bookId!=''){
//首先需要使用lay-value来确定需要设置哪个元素自动选择
var select = 'dd[lay-value=' + bookId + ']';
//触发点击事件,实现自动选择
$('#bookList).siblings("div.layui-form-select").find('dl').find(select).click();
}
//已测试成功
个人感觉如下写法也是可以搞定:
let bookId = '[[${bookId}]]';
$("#bookList").val($(bookId);//atype是select的id
form.render('select');
注意:form.render必须加否则不能正常渲染,动态设置layui的select设置选中完成。
var bookId=$("#bookId").val();//假设获取隐藏域中的值
//根据值让option选中
$("#bookList option[value='"+bookId+"']").attr("selected","selected");
//这个没有测试,明天我会自己测试,是否重新渲染?测试完毕,需要渲染
form.render('select');
问题:多个标签渲染如何处理? 参考的文档:复选框
var bookId = $("select[name='bookList']").val();//获取选中的值