2013-01-22 37 views
2

我想做一个简单的方法来隐藏/显示内容时,用户单击一个单选按钮。我不想一遍又一遍地使用ID,我想用一个更通用的选择器来使用类,这样我就可以在整个网站中重新应用它。选择第二个最接近的类

我想我不是在父div(.radio-show)之外找到.next .radio-show-content?

$('.radio-show input:radio').click(function() { 
     $(this).closest('div').next().find('.radio-show-content').fadeToggle(250).toggleClass('hide'); 
}); 


<div class="radio-show" > 
<label class="radio span1"> 
    <input type="radio" name="project" value="option1" checked> 
    Yes 
</label> 
<label class="radio span1"> 
    <input type="radio" name="project" value="option2"> 
    No 
</label> 
</div> 

<hr /> 
<div class="radio-show-content"><!-- yes --> 
    Show this if Yes 
</div> 
<div class="radio-show-content hide"><!-- no--> 
    Show this if No 
</div> 

回答

0

.next正在变得<hr>。真的,没有必要上去DOM树。你可以使用:

$(".radio-show-content").fadeToggle(250).toggleClass('hide') 

然而,这可能并不想要什么,它不选择特定.radio-show-content做。您可以基于单选按钮索引进行链接(使用.index获取并获取-show-content.eq),或者只使用.hide的CSS转换并持续切换。

+0

啊您的权利,没有必要去了DOM树。但是,如果我想限制只选择NEXT 2 .radio-show-content类,该怎么办?例如。在同一页面上有多个无线电对显示/隐藏特定于离它最近的最近的.radio-show-content? – simple

+0

@简单,听起来相当复杂..你必须通过类链接单选按钮到广播内容,或使用相应的索引,如我在我的回答 –

0

我想你应该尝试没有.find()

$(this).closest('div').next('.radio-show-content').fadeToggle(250).toggleClass('hide'); 
0

这个插件正是这种写入。 免责声明:我写这

http://techfoobar.com/jquery-next-in-dom/

$('.radio-show input:radio').click(function() { 
    $(this).nextInDOM('.radio-show-content').fadeToggle(250).toggleClass('hide'); 
}); 
+0

中所述注意:但在你的情况下,如果你只有一个元素匹配''.radio-show-content'',只需做一个简单的选择器,就像Explosion Pills所回答的那样。在这种情况下使用插件将是一个矫枉过正的问题。 – techfoobar