简体   繁体   English

选择元素和后续文本

[英]Select element and subsequent text

I'm having following markup: 我有以下标记:

<div class="controls">
  <input type="radio" id="sex" name="sex" value="m"> Boy
  <input type="radio" id="sex" name="sex" value="f"> Girl
  <input type="radio" id="sex" name="sex" value="t"> Twins
</div>

How can I select each radio button and it's subsequent text. 如何选择每个单选按钮及其后续文本。 My goal is to wrap both in a label, so the output would be: 我的目标是将两者包装在标签中,因此输出将是:

<div class="controls">
  <label><input type="radio" id="sex" name="sex" value="m"> Boy</label>
  <label><input type="radio" id="sex" name="sex" value="f"> Girl</label>
  <label><input type="radio" id="sex" name="sex" value="t"> Twins</label>
</div>

Unfortunately, the markup is created by a CMS. 不幸的是,标记是由CMS创建的。 (It also adds id="sex" multiple times, blergh). (blergh,它还会多次添加id="sex" )。

The shortest I can think of: 我能想到的最短的:

 $('.controls :radio').each(function() { $(this).add(this.nextSibling).wrapAll('<label>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="controls"> <input type="radio" id="sex" name="sex" value="m"> Boy <input type="radio" id="sex" name="sex" value="f"> Girl <input type="radio" id="sex" name="sex" value="t"> Twins </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM