2016-07-25 2 views
0

내가 dt 요소 중 하나에 배치되어있는 동안 다음 요소 인 dt 요소로 이동하려고합니다. 이것을 어떻게 할 수 있습니까?dom 트리에서 다음으로 이동하는 형제를 찾는 방법

<dl class="accordion"> 
    <dt>Select Category</dt> 
    <dd></dd> 

    <dt>select product</dt> 
    <dd></dd> 
</dl> 
(function($) { 
    var allPanels = $('.accordion > dd').hide(); 
    $('.accordion > dd:first-of-type').show(); 
    $('.accordion > dt:first-of-type').addClass('accordion-active'); 

    jQuery('.accordion > dt').on('click', function() { 
     $this = $(this); 
     $target = $this.next(); 
     if (!$this.hasClass('accordion-active')) { 
      $this.parent().children('dd').slideUp(); 
      jQuery('.accordion > dt').removeClass('accordion-active'); 
      $this.addClass('accordion-active'); 
      $target.addClass('active').slideDown(); 
     }  
     return false; 
    }); 
})(jQuery); 
+0

thisdt은 무엇인가라는 질문의 코드에서

,이 다음 업데이트를 제공합니다? –

+0

그것은 작동하지 않습니다 ... $ this.next ("dt")는 어떻게 든 클릭 된 동일한 요소를 가리 킵니다 ... dom의 다음 dt 요소를 원합니다 –

+0

'$ target = $ this.nextAll ('dt') .eq (0);'?! –

답변

4
JQuery와의 확실한 옵션이 될 것으로 보인다 무엇

: .next() 항상에만 .next(filter)는 여전히 바로 다음 형제를 반환하는 필터를 적용, 바로 다음 형제를 반환하기 때문에, .next("dt")가 아니라, 단지 그것을 경우 필터

jQuery를 두 가지 대안을 제공 일치 : .nextUntil().nextAll()

을이 같이 사용할 수 있습니다

nextdt = thisdt.nextUntil("dt").next(); 
nextdt = thisdt.nextAll("dt").first(); 

다음 nextUntil은 일치 할 때까지 다음 형제를 가져오고 nextAll은 모든 일치하는 항목을 가져옵니다. 그러면 first()가 필요합니다.

jQuery('.accordion > dt').on('click', function() { 
    $this = $(this); 
    $target = $this.nextAll("dt").first(); 

예 바이올린 : https://jsfiddle.net/0wk1mkeq/

+0

+1 당신이 옳다, 그것은 명백하지 않다. 만약 당신의 설명없이 추측해야만한다면,'next ('filter')'는 필터와 일치하는 다음 요소를 반환 할 것이고 그것은 잘못되었을 것입니다. 유용한 설명. – BobRodes

관련 문제