2014-09-06 58 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