2010-06-17 35 views
3

我想找到最接近的tr也匹配特定的類名稱。選擇器不返回任何匹配。我不瞭解什麼?JQuery使用最近(「element.class」)

例如:

<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 2010-06-17 19:01:35