You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Input元素中获取关联Label的文本值?含jQuery代码示例

如何从Input元素获取关联的文本(或Label文本)

首先得提一句:你当前的HTML代码里没有<label>标签哦,那些数字(6、7、8、9)是直接写在<input>元素后面的文本节点,所以你用$('label[for="8"]')肯定找不到任何元素~ 下面分两种情况给你解决方案:

情况1:如果后续改成标准的Input+Label关联结构

如果之后把HTML调整为符合规范的结构(用id和for属性关联input和label),比如:

<div class="ad_numbers">
  <input type="radio" name="ad_pos" id="ad_6" value="6" />
  <label for="ad_6">6</label><br>
  <input type="radio" name="ad_pos" id="ad_7" value="7" />
  <label for="ad_7">7</label><br>
  <input type="radio" name="ad_pos" id="ad_8" value="8" checked/>
  <label for="ad_8">8</label><br>
  <input type="radio" name="ad_pos" id="ad_9" value="9" />
  <label for="ad_9">9</label><br>
</div>

这时候要获取value为8的input对应的label文本,有两种常用写法:

  • 通过for属性匹配:
const targetInput = $('input[name="ad_pos"][value="8"]');
const labelText = $(`label[for="${targetInput.attr('id')}"]`).text();
console.log('LABEL:', labelText); // 输出 "8"
  • 利用DOM相邻关系(label紧跟在input后面):
const labelText = $('input[name="ad_pos"][value="8"]').next('label').text();
console.log('LABEL:', labelText);

情况2:针对你现在的HTML结构(无Label标签)

因为当前的数字是直接放在input后面的文本节点(不是标签元素),所以需要获取input的相邻文本节点来拿到内容:

  • 原生DOM+jQuery结合的写法(简单直接):
const targetInput = $('input[name="ad_pos"][value="8"]')[0];
// nextSibling获取下一个节点(这里是文本节点),trim去掉多余空格
const labelText = targetInput.nextSibling.textContent.trim();
console.log('LABEL:', labelText); // 输出 "8"
  • 纯jQuery筛选文本节点的写法:
const labelText = $('input[name="ad_pos"][value="8"]')
  .contents()
  .filter(function() {
    return this.nodeType === 3; // 筛选出文本节点
  })
  .text()
  .trim();
console.log('LABEL:', labelText);

如果你的需求是获取当前选中的单选框对应的文本,还可以这样写:

const checkedInput = $('input[name="ad_pos"]:checked');
const checkedText = checkedInput[0].nextSibling.textContent.trim();
console.log('当前选中的文本:', checkedText);

内容的提问来源于stack exchange,提问作者Zorgan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:54:04