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

如何获取已选中input对应的关联label标签显示文本?

问题:替换单选框value为对应label文本插入到指定容器

场景结构

HTML结构如下:

<div class="form-item">
  <input data-drupal-selector="edit-field-entity-product-category-target-id-verf-365-lp1ntlq5bca" type="radio" id="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" name="field_entity_product_category_target_id_verf" value="365" class="input input--radio form-input form-radio">
  <label for="edit-field-entity-product-category-target-id-verf-365--Lp1nTLQ5bcA" class="option">Headwear</label>
</div>

原代码问题

我编写的jQuery代码如下,当前执行后,tags-container容器插入的是input的value值(如365),但需要改成对应的label标签文本(如Headwear):

function () {
  let formInput = $(".form-input");
  let html = "<span>";

  $.each(formInput, function() {
    let $this = $(this);
    if($this.is(":checked")) {
      html += $this.val();
    }
  });
  html += "</span>";
  $(".product-list-wrapper .rows-wrapper .tags-container").html(html);
  $(".rows-wrapper").show();
}

修改方案

有两种可靠方式获取对应label的文本,按需选择:

方法1:利用相邻元素关系获取

因为input和label是同级相邻的,直接用next()定位相邻label后取文本,这种方式DOM遍历效率更高:

function () {
  let formInput = $(".form-input");
  let html = "<span>";

  $.each(formInput, function() {
    let $this = $(this);
    if($this.is(":checked")) {
      // 替换val()为获取相邻label的文本
      html += $this.next(".option").text();
    }
  });
  html += "</span>";
  $(".product-list-wrapper .rows-wrapper .tags-container").html(html);
  $(".rows-wrapper").show();
}

方法2:通过id与for属性匹配获取

如果input和label不是严格相邻的,这种方法兼容性更强——只要label的for属性与input的id对应,不管位置在哪都能定位到:

function () {
  let formInput = $(".form-input");
  let html = "<span>";

  $.each(formInput, function() {
    let $this = $(this);
    if($this.is(":checked")) {
      // 通过input的id匹配label的for属性,再取文本
      html += $(`label[for="${this.id}"]`).text();
    }
  });
  html += "</span>";
  $(".product-list-wrapper .rows-wrapper .tags-container").html(html);
  $(".rows-wrapper").show();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:11:37