2011-02-15 5 views
7

는 내가 가지고 :jquery : closest ('h3') selector?

<ul class="rating"> 
    <h3>Like this</h3> 
    <li class="rating-number"> 
     <div id="iLikeThis" class="iLikeThis"> 
      <span class="counter">2</span> 
     </div> 
    </li> 
</ul> 

이 내 jQuery 코드

$('.iLikeThis .counter').each(function() { 
     $(this).parent().parent().parent().children('h3').text('You like this'); 
     $(this).parent().addClass('like'); 
}); 

가장 가까운 H3 요소를 선택하는 더 나은 방법이 있나요. 3 배의 parent()에서는 작동하지만 가장 가까운 ('h3)에서는 작동하지 않습니다.

왜?

+1

이것은 잘못된 HTML을. 'ul'의 자식으로'h3'을 사용할 수 없습니다. 이와 같이 깨진 HTML을 사용하면 브라우저가 올바른 일을하는지 알 수 없습니다. – RoToRa

+0

@RoToRa : 좋은 캐치. – BoltClock

+0

감사합니다! 너는 그걸 리의 자식으로 가질 수 있니? – matt

답변

13

.counter의 부모가 아닌 h3은 작동하지 않습니다. 대신 .rating.closest()를 사용하고 h3 찾을 :

$(this).closest('.rating').children('h3').text('You like this');