我想制作一个简单的方法来在用户单击单选按钮时隐藏/显示内容。我不想一遍又一遍地使用 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>
最佳答案
.next
正在获取<hr>
。实际上,没有必要遍历 DOM 树。您可以只使用:
$(".radio-show-content").fadeToggle(250).toggleClass('hide')
但是,这可能不会达到您想要的效果,因为它没有选择特定的 .radio-show-content
。您可以基于单选按钮索引进行链接(使用 .index
获取并使用 -show-content
获取 .eq
),或者仅使用 CSS 过渡 .hide
。并一致地切换它。
关于jquery - 选择下一个最接近的类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14464696/