2011-12-21 160 views
0

我有一組單選按鈕,我試圖做的是循環並隱藏任何未選中的按鈕(addClass .hiddenRadio)的收音機和標籤。這樣做的另一面是,我需要在另一個事件再次讓他們點擊通過單選按鈕循環,隱藏未選中的按鈕

<input class="radio" type="radio" name="sex_1" value="male" /><label>Male</label> 
<input class="radio" type="radio" name="sex_1" value="female" /><label>Female</label> 

<input class="radio" type="radio" name="sex_2" value="male" /><label>Male</label> 
<input class="radio" type="radio" name="sex_2" value="female" /><label>Female</label> 

男 女的代碼

+0

你真的應該加上'id'屬性你'input'元素,以及相應的'for'屬性到你的'標籤'元素。否則,標籤將無法按預期工作。 – 2011-12-21 14:48:52

回答

-1

查看哪些選擇具有radio類的所有選中的輸入和隱藏相應的標籤如下:

$(".radio:not(:checked)").each(function() { 
    // If you the hiddenRadio class added to both 
    $(this).addClass("hiddenRadio").next().addClass("hiddenRadio"); 

    // Otherwise if you just want to hide the label 
    $(this).addClass("hiddenRadio").next().hide(); 
}); 
3

兩條線真的夠:

$("input[type=radio]:not(:checked)").addClass("hiddenRadio"); 
$("input[type=radio]:not(:checked) + label").addClass("hiddenLabel"); 

使用無需循環each()或使用next()手動查找標籤 - 讓選擇器完成工作!

這裏是展示一個的jsfiddle(沒有隱瞞,但改變顏色)

http://jsfiddle.net/bZcHq/

而且,也沒有必要添加class='radio'每一個單選按鈕。只要您不打算支持IE6,屬性選擇器[type=radio]就足夠了。

+0

您還需要添加兄弟標籤 – Mathletics 2011-12-21 14:38:05

+0

「radio」類型的每個元素都是'input'因此'$(「[type = radio]:not(:checked)」)'也可以工作 – abuduba 2011-12-21 14:42:38

+1

@abuduba包括標籤該類在jQuery(Sizzle)中速度更快http://www.artzstudio.com/2009/04/jquery-performance-rules/ – Mathletics 2011-12-21 14:50:49

0

怎麼是這樣的:http://jsfiddle.net/GTzL4/4/

HTML

<input class="radio" type="radio" name="sex_1" value="male" checked /><label>Male</label> 
<input class="radio" type="radio" name="sex_1" value="female" /><label>Female</label> 

    <input class="radio" type="radio" name="sex_2" value="male" /><label>Male</label> 
<input class="radio" type="radio" name="sex_2" value="female" checked /><label>Female</label> 

<button onclick="hideUnSelected()">Hide</button> 
<button onclick="showAll()">Show</button> 

CSS

.hidden{display:none;} 

JS

function hideUnSelected(){ 
    $('.radio:not(:checked)').each(function(){ 
     $(this).addClass('hidden').next('label').addClass('hidden'); 
    }); 
} 
function showAll(){ 
    $('.radio').each(function(){ 
     $(this).removeClass('hidden').next('label').removeClass('hidden'); 
    }); 
}