<option th:each="center : ${helpCenter}" th:value="${center.dictSort}" th:text="${center.dictLabel}"
th:selected="${center.dictSort != jdptAnnouncement.type} ? '' : 'selected'"></option>
在templates中这个代码的意思局势 遍历一个下拉框
如果center.dictSort !=jdptAnnouncement.type成立 则selected=""
相反则 selected="selected";
但是这里有个坑就是 只添加selected属性,不加任何值,同样会使该选项被默认选中
如果selected="" 它也会给默认值 给selected="selected"
运行结果可以开出 也就是在这里th:selected是没用的
那应该怎么办呢!!
可以用th:attr来动态的设置selected属性
<option th:each="center : ${helpCenter}" th:value="${center.dictSort}" th:text="${center.dictLabel}"
th:attr="selected=${center.dictSort == jdptAnnouncement.type} ? 'selected' : null"></option>
这里是一起发开的人员更换了数据 但是不影响 可以看到只有一个生效
那我这里在想 如果值为空就可以生效 那如果我用th:selected也为空呢
<option th:each="center : ${helpCenter}" th:value="${center.dictSort}" th:text="${center.dictLabel}"
th:selected="${center.dictSort != jdptAnnouncement.type} ? null : 'selected'"></option>
和上面的结果一样 生效!
所以selected只要是等于一个值无论值为''''或里面有值都会展示 避坑