我有一个表单,其中包含一些我不想显示的可选字段,除非用户特别启用它们。我正在努力找出 .closest()
jQuery 中的方法希望得到一些指导。有多种这样的形式,所以我不想为了 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>
我认识将军if
语句有效,因为使用 console.log("checked")
时和 console.log("unchecked")
在if
里面, 有用。我想我对 .closest
处理不当方法,但我不知道如何/为什么。
编辑:为了澄清起见,我试图做到这一点,所以当复选框被选中时最接近 .stage-dates
div 淡入,未选中时淡出。
最佳答案
$.closest()
返回所选元素的第一个祖先。它不会搜索整个 DOM 并返回最接近的匹配项。要在这里使用 $.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>
关于javascript - 选中复选框时淡入/淡出最接近的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41841931/