选择下一个最近的班级

时间:2013-01-22 17:38:35

标签: jquery

当用户点击单选按钮时,我想制作一个隐藏/显示内容的简单方法。我不是一遍又一遍地使用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>

3 个答案:

答案 0 :(得分:0)

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

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

然而,这可能不会做你想要的,因为它没有选择特定的.radio-show-content。您可以根据单选按钮索引进行链接(使用.index获取并使用-show-content获取.eq),或者只使用.hide进行CSS转换并对其进行一致切换。

答案 1 :(得分:0)

我认为你应该在没有.find()

的情况下尝试
$(this).closest('div').next('.radio-show-content').fadeToggle(250).toggleClass('hide');

答案 2 :(得分:0)

这个插件就是为此编写的。 免责声明:我写了

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

$('.radio-show input:radio').click(function() {
    $(this).nextInDOM('.radio-show-content').fadeToggle(250).toggleClass('hide');
});
相关问题