Jquery 在标签的for属性中添加输入ID
我正在尝试获取输入的ID,并将其添加到=ID的标签中。 以下是html:Jquery 在标签的for属性中添加输入ID,jquery,Jquery,我正在尝试获取输入的ID,并将其添加到=ID的标签中。 以下是html: <form> <div class="search-row-location search-row-checkbox-multiple"> <label for="location" class="search-label">Location</label> <div class="field"> &
<form>
<div class="search-row-location search-row-checkbox-multiple">
<label for="location" class="search-label">Location</label>
<div class="field">
<input checked="" name="location[]" id="location_0" value="0" class="input-field=" type="checkbox">
<label class="search-checkbox-label">All Locations</label>
<input name="location[]" id="location_1" value="1" class="input-field" type="checkbox">
<label class="search-checkbox-label">Sydney</label>
<input name="location[]" id="location_2" value="1" class="input-field" type="checkbox">
<label class="search-checkbox-label">Paris</label>
</div>
</div>
<div class="search-row-price search-row-checkbox-multiple">
<label for="price" class="search-label">Price</label>
<div class="field">
<input checked="" name="price[]" id="price_0" value="0" class="input-field=" type="checkbox">
<label class="search-checkbox-label">All Prices</label>
<input name="price[]" id="price_1" value="1" class="input-field" type="checkbox">
<label class="search-checkbox-label">100$</label>
<input name="price[]" id="price_2" value="1" class="input-field" type="checkbox">
<label class="search-checkbox-label">200$</label>
</div>
</div>
</form>
我正在获取第一个输入的id,即,。所有标签中的位置0。如何使其工作?使用和循环来实现这一点
jQuery('.search-checkbox-label').each(function(){
jQuery(this).attr('for', jQuery( this ).prev('.input-field').attr('id'));
});
片段
jQueryfunction{
jQuery'.search复选框标签'.eachfunction{
jQuerythis.attr'for',jQuerythis.prev'。输入字段'.attr'id';
};
};
地方
所有地点
悉尼
巴黎
价格
所有价格
100$
200$
解决问题谢谢:在你发布的那一秒之前就收到了:现在我非常确定!有没有理由不能修改HTML源代码?从长远来看,这将是最好的解决办法。使用JS作为解决UI问题的拐杖不是一件好事。不,我无法编辑HTML源代码。如果您使用复选框上的输入字段,则“输入字段”将不起作用。
jQuery('.search-checkbox-label').each(function(){
jQuery(this).attr('for', jQuery( this ).prev('.input-field').attr('id'));
});
jQuery('.search-checkbox-label').each(function() {
jQuery( this ).attr('for', jQuery( this ).prev('.input-field').attr('id'));
});