簡體   English   中英

jQuery無法使用next / closest選擇元素

[英]jquery unable to select element using next/closest

我的頁面上有以下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>

我有以下JS代碼;

$(".expandCollapseSection").click(function (event) {
    if ($(this).prop("checked")) {
        $(this).next('.contentDiv').slideDown('slow');
    } else {
        $(this).next('.contentDiv').slideUp('slow');
    }
}); 

現在我的問題是$(this).next('.contentDiv')沒有選擇contentDiv

我什至嘗試使用$(this).closest('.contentDiv')

但是仍然沒有選擇。

只是添加$(".contentDiv")確實會獲得div。

我在這里做錯什么了嗎?

使用siblings( ".selected" )

$(".expandCollapseSection").click(function (event) {
    if ($(this).prop("checked")) {
        $(this).siblings('.contentDiv').slideDown('slow');
    } else {
        $(this).siblings('.contentDiv').slideUp('slow');
    }
});  

演示

你可以試試:

$(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的答案是正確的。

但是你可以簡單地使用

$(this).parent().find('.contentDiv');

效率略高,因為您不必查找最接近的div。

試試這個代碼,

$(".expandCollapseSection").click(function (event) {
    if ($(this).prop("checked")) {
        $(this).closest('#c2').find('.contentDiv').slideDown('slow');
    } else {
        $(this).closest('#c2').find('.contentDiv').slideUp('slow');
    }
}); 

您也可以使用nextAll並縮短代碼,如下所示。

$(".expandCollapseSection").change(function (event) {
    var div = $(this).nextAll('.contentDiv');
    var func = this.checked ? 'slideDown' : 'slideUp';
    div[func]("slow");
});

演示@ 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM