* 获取元素的标签文本
(element)
| 22 | * 获取元素的标签文本 |
| 23 | */ |
| 24 | function getLabelText(element) { |
| 25 | let labelText = ''; |
| 26 | const id = element.id; |
| 27 | |
| 28 | // 1. 查找 <label for="id"> |
| 29 | if (id) { |
| 30 | const label = document.querySelector(`label[for="${id}"]`); |
| 31 | if (label) labelText += label.innerText; |
| 32 | } |
| 33 | |
| 34 | // 2. 查找父级 <label> |
| 35 | const parentLabel = element.closest('label'); |
| 36 | if (parentLabel) labelText += parentLabel.innerText; |
| 37 | |
| 38 | // 3. 查找 aria-label |
| 39 | const ariaLabel = element.getAttribute('aria-label'); |
| 40 | if (ariaLabel) labelText += ariaLabel; |
| 41 | |
| 42 | // 4. 查找 placeholder |
| 43 | const placeholder = element.getAttribute('placeholder'); |
| 44 | if (placeholder) labelText += placeholder; |
| 45 | |
| 46 | // 5. 查找前置文本节点 (简单的启发式) |
| 47 | // 很多表格布局中,label 在 input 的前一个 td 或兄弟节点 |
| 48 | let previous = element.previousElementSibling; |
| 49 | while (previous) { |
| 50 | if (previous.tagName === 'LABEL' || previous.tagName === 'SPAN' || previous.tagName === 'TD' || previous.tagName === 'TH') { |
| 51 | labelText += previous.innerText; |
| 52 | break; |
| 53 | } |
| 54 | previous = previous.previousElementSibling; |
| 55 | } |
| 56 | |
| 57 | return labelText.toLowerCase().replace(/\s+/g, ''); |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * 通过标签文本查找字段 |