[英]fadeIn/fadeOut closest div when checkbox is checked
I have a form with some optional fields that I don't want to be displayed unless the user specifically enables them. 我有一个带有一些可选字段的表单,除非用户专门启用它们,否则我不想显示这些字段。 I am struggling to figure out the
.closest()
method in jQuery hoping for some guidance. 我正在努力找出jQuery中的
.closest()
方法,以期寻求一些指导。 There are multiple forms like this so I didn't want to us an #id for the sake of DRY. 像这样有多种形式,所以我不想为了DRY而给我们#id。
$('.enable-stage').change(function() { if ($(this).is(':checked')) { $(this).closest('.stage-dates').fadeIn("slow").toggleClass("hidden"); } else { $(this).closest('.stage-dates').fadeOut("slow").toggleClass("hidden"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="stage"> <h3>Stage Name</h3> <label><input type="checkbox" class="enable-stage"> Enable Stage</label> <div class="stage-dates hidden"> <input type="date"> </div> </div>
I know the general if
statement is working because when using console.log("checked")
and console.log("unchecked")
inside the if
, it works. 我知道一般的
if
语句是有效的,因为在if
使用console.log("checked")
和console.log("unchecked")
if
,它可以工作。 I think I am mishandling the .closest
method but I cannot figure out how/why. 我认为我对
.closest
方法的处理不当,但是我不知道如何/为什么。
Edit: for clarification, I'm trying to make it so when the checkbox is checked the closest .stage-dates
div fades in and when it's unchecked it fades out. 编辑:为澄清
.stage-dates
,我正在尝试使它处于选中状态,以便在选中复选框时,最接近的.stage-dates
div淡入,而在未选中它时则淡出。
$.closest()
returns the first ancestor of the selected element. $.closest()
返回所选元素的第一个祖先。 It doesn't search the entire DOM and return the closest match. 它不会搜索整个DOM并返回最接近的匹配项。 To use
$.closest()
here, we can find the closest label
(since label
is an ancestor to the checkbox), then use $.next()
to target .stage-dates
要在这里使用
$.closest()
,我们可以找到最接近的label
(因为label
是复选框的祖先),然后使用$.next()
定位.stage-dates
$('.enable-stage').change(function() { var $closest = $(this).closest('label').next('.stage-dates'); if ($(this).is(':checked')) { $closest.fadeIn("slow").toggleClass("hidden"); } else { $closest.fadeOut("slow").toggleClass("hidden"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="stage"> <h3>Stage Name</h3> <label><input checked type="checkbox" class="enable-stage"> Enable Stage</label> <div class="stage-dates hidden"> <input type="date"> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.