2010-06-17 3 views
3

특정 클래스 이름과 일치하는 가장 가까운 tr을 찾으려고합니다. 선택기는 일치하는 항목을 반환하지 않습니다. 나는 무엇을 이해하지 못합니까? 예를 들어Closest ("element.class")를 사용하는 JQuery

: 가장 가까운

<table> 
<tbody class="category" id="cat-1"> 
<tr class="category-head"> 
    <th>Category 1</th> 
</tr> 
    <tr class="category-item"> 
    <th>Item 1</th> 
    </tr> 
    <tr> 
    <td>This is a description of category item 1</td> 
    </tr> 
    <tr> 
    <td><input type="text" name="c1_i1_input" id="c1_i1_input" class="category-item-input" /></td> 
    </tr> 
    <tr class="category-item"> 
    <th>Item 2</th> 
    </tr> 
    <tr> 
    <td>This is a description of category item 2</td> 
    </tr> 
    <tr> 
    <td><input type="text" name="c1_i2_input" id="c1_i2_input" class="category-item-input" /></td> 
    </tr> 
    </tbody> 
</table> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $(".category-item-input").change(function() { 
      //this works, returning the closest tr 
      alert($(this).closest("tr").html()); 

      //this returns null? 
      alert($(this).closest("tr.category-item").html()); 
     }); 

    });</script> 

답변

8

가장 가까운 조상 요소는 DOM에서가 아니라 가까운을 찾습니다. 입력이 들어있는 tr에는 클래스가 없으므로 선택기가 실패합니다. 가장 가까운 tr을 찾고 그 다음에 그 이전의 형제 인 tr을 찾아야합니다.

$(this).closest('tr').prevAll('tr.category-item:last'); 
+0

답변을 주셔서 감사합니다. – Rokal

관련 문제