2014-09-06 52 views
0

我想将每个两个标签都包装在div中。这些标签是输入单选类型按钮的父项,我想将它们定位为输入无线电类型的父项,以避免打包我网站上的任何其他现有标签(可能有更好的方法来定位这些标签)。这里是的jsfiddle http://jsfiddle.net/Lqu8rcLb/2/jQuery将div中的每个两个标签打包

<form id="myform" method="post" action=""> 
<fieldset> 
<dl> 
<dd> 
    <label> 
    <input type="radio" name="radio1" value="radio1"> 
    </label> 
    <label> 
    <input type="radio" name="radio1" value="radio2"> 
    </label> 
</dd> 
</dl>  
     <br></br> 
<dd> 
    <label> 
    <input type="radio" name="radio2" value="radio3"> 
    </label> 
    <label> 
    <input type="radio" name="radio2" value="radio4"> 
    </label> 
</dd> 
</dl>  
</fieldset> 
</form> 

的jQuery:

$('input:radio').parent().each(function() { 
    $(this).wrapAll("<div class="wrapped-labels"></div>"); 
}); 

但jQuery代码不工作,我尝试过许多其他的可能性,最近的一次是包裹在一个div每个标签,但是这是不是我想要的,因为我想要一个div中的两个标签。

+1

'“

”双引号中的双引号中使用双引号会产生问题。你想使内部引号为单个或用'\' – GillesC 2014-09-06 16:18:23

+0

感谢您指出这一点。但正如我所说,它包装每个标签,而不是两个。 – Eddi 2014-09-06 16:22:17

回答

0

你可能想只得到一个标签,那么兄弟标签添加到集合,然后包裹在一个div

$('#myform label:has(input[type="radio"]) + label:has(input[type="radio"])').each(function() { 
    $(this).add($(this).siblings('label')).wrapAll('<div class="wrapped-labels"></div>') 
}); 

FIDDLE

另一种方式来做到这一点,将be

$('input[type="radio"]').parent().each(function() { 
    if (! $(this).closest('.wrapped-labels').length) 
     $(this).add($(this).siblings('label')).wrapAll('<div class="wrapped-labels"></div>'); 
}); 
+0

快速而有用。非常感谢。任何意见,我应该如何包括输入类型复选框呢?或者我应该简单地重复这段代码并用type =“checkbox”编辑type =“radio”的部分? – Eddi 2014-09-06 16:28:40

+0

我喜欢他们,但我想我会去第一个:)。 – Eddi 2014-09-06 16:31:46

+0

您是否真的需要检查类型,并且是否有任何方法可以将其反转,如排除文本输入 - >'[type!=“text”]''等等。否则,第二个可能最容易扩展到复选框 - > ** http://jsfiddle.net/Lqu8rcLb/4/** – adeneo 2014-09-06 16:32:22