Skip to content

多值类匹配

标记选择器(Markup Selectors)会将 class 属性视为多值属性,因此即使元素拥有多个 class 值,也可以对该属性应用选择器进行匹配。

例如,div.two 会匹配 <div class="one two three" />

一、核心规则与直观示例

1. 基础匹配逻辑

HTML 中 class 属性允许通过空格分隔多个类名(如 class="one two three"),Thymeleaf 标记选择器会拆分这些类名并独立匹配:

  • 选择器语法:标签名.类名(如 div.two)、或直接 .类名(匹配所有标签);
  • 匹配结果:只要元素的 class 包含该类名,无论是否有其他类名,都会被选中。

2. 经典示例验证

html
<!-- 目标元素:包含 one、two、three 三个类名 -->
<div class="one two three">测试元素</div>

以下选择器均可匹配该元素:

标记选择器匹配结果说明
div.two✅ 匹配标签为 div + class 包含 two
.two✅ 匹配所有标签 + class 包含 two(不限标签类型)
div.one✅ 匹配标签为 div + class 包含 one
div.three✅ 匹配标签为 div + class 包含 three
div.one.two✅ 匹配标签为 div + 同时包含 one 和 two(多类名组合匹配)
div.four❌ 不匹配class 中无 four 类名

二、实际应用场景(Thymeleaf 核心用法)

这个规则主要用于 Thymeleaf 的「解耦逻辑(Decoupled Logic)」和「片段引用(Fragment Expressions)」,是模板开发中高频用到的特性:

场景 1:解耦逻辑(Decoupled Logic)

.th.xml 解耦逻辑文件中,通过类选择器绑定 Thymeleaf 逻辑,无需关心元素是否有多个类名:

xml
<!-- 解耦逻辑文件:为所有 class 包含 "order-item" 的 div 绑定遍历逻辑 -->
<logic>
  <attr sel="div.order-item" th:each="item : ${order.items}">
    <attr sel="span.name" th:text="${item.name}" />
    <attr sel="span.price" th:text="${item.price}" />
  </attr>
</logic>

即使页面中的元素是 <div class="order-item bg-gray mb-2">div.order-item 仍能精准匹配并绑定逻辑。

场景 2:片段引用(Fragment Expressions)

引用模板片段时,通过类选择器定位元素,兼容多类名场景:

html
<!-- 引用模板中 class 包含 "user-card" 的 div 片段 -->
<div th:replace="~{common :: div.user-card}"></div>

<!-- 被引用的片段(class 包含多个值) -->
<footer th:fragment="footer">
  <div class="user-card shadow rounded p-3">
    <span th:text="${user.name}">用户名</span>
  </div>
</footer>

场景 3:组合类名精准匹配

若需匹配「同时包含多个类名」的元素,可拼接类选择器(无空格),实现更精准的筛选:

html
<!-- 仅匹配 class 同时包含 "btn" 和 "primary" 的 button -->
<button class="btn primary">主按钮</button>
<button class="btn secondary">次按钮</button>

<!-- 选择器:仅匹配第一个按钮 -->
<th:block th:replace="~{components :: button.btn.primary}"></th:block>

三、关键注意事项

  1. 与 CSS 选择器完全兼容:Thymeleaf 标记选择器的类匹配规则和 CSS 选择器一致,前端开发者无需额外学习;
  2. 类名大小写敏感div.Two 无法匹配 class="two",需保证类名大小写完全一致;
  3. 空格的特殊含义:选择器中「空格表示后代关系」,而非类名分隔——例如 div .two 匹配「div 后代中 class 包含 two 的元素」,而非「class 包含 div 和 two 的元素」;
  4. 空值/无 class 处理:若元素无 class 属性(或 class=""),任何类选择器都无法匹配。

总结

  1. 核心规则:Thymeleaf 标记选择器将 class 视为多值属性,只需匹配其中一个类名即可命中元素;
  2. 典型示例div.two 可匹配 <div class="one two three" />,是最直观的体现;
  3. 核心价值:兼容 HTML 多类名写法,简化模板逻辑绑定/片段引用的选择器编写;
  4. 易错点:区分选择器中「空格(后代关系)」和「点(类名)」的不同含义,避免匹配错误。