[英]jquery unable to select element using next/closest
I have the following HTML on my page; 我的页面上有以下HTML;
<div id="c2">
<input type="checkbox" class="expandCollapseSection" id="my_chk">
<span>Header</span>
<div style="" class="contentDiv">
<div class="oj-inputtext oj-form-control oj-component">some things</div>
</div>
</div>
I have the following JS code; 我有以下JS代码;
$(".expandCollapseSection").click(function (event) {
if ($(this).prop("checked")) {
$(this).next('.contentDiv').slideDown('slow');
} else {
$(this).next('.contentDiv').slideUp('slow');
}
});
Now my question is $(this).next('.contentDiv')
does not select the contentDiv 现在我的问题是
$(this).next('.contentDiv')
没有选择contentDiv
I even tried using $(this).closest('.contentDiv')
我什至尝试使用
$(this).closest('.contentDiv')
But still does not select. 但是仍然没有选择。
Just to add $(".contentDiv")
does get the div though. 只是添加
$(".contentDiv")
确实会获得div。
Am I doing something wrong here? 我在这里做错什么了吗?
You can try: 你可以试试:
$(this).closest('div').find('.contentDiv');
$(".expandCollapseSection").click(function (event) { if ($(this).prop("checked")) { $(this).closest('div').find('.contentDiv').css({'color':'red'}); } else { $(this).closest('div').find('.contentDiv').css({'color':'green'}); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="c2"> <input type="checkbox" class="expandCollapseSection" id="my_chk"> <span>Header</span> <div style="" class="contentDiv"> <div class="oj-inputtext oj-form-control oj-component">some things</div> </div> </div> <div id="c3"> <input type="checkbox" class="expandCollapseSection" id="my_chk"> <span>Header</span> <div style="" class="contentDiv"> <div class="oj-inputtext oj-form-control oj-component">some things</div> </div> </div>
kapantzak's answer is correct. kapantzak的答案是正确的。
However you could simply use 但是你可以简单地使用
$(this).parent().find('.contentDiv');
Slightly more efficient, as you don't have to find closest div. 效率略高,因为您不必查找最接近的div。
Try This Code, 试试这个代码,
$(".expandCollapseSection").click(function (event) {
if ($(this).prop("checked")) {
$(this).closest('#c2').find('.contentDiv').slideDown('slow');
} else {
$(this).closest('#c2').find('.contentDiv').slideUp('slow');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.