如何获取已选中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
相关产品推荐
相关产品推荐

