JQuery使用closest("元素.类名")方法

3
我将尝试寻找最接近的 tr 并匹配特定的类名。但选择器没有返回任何匹配项。我可能理解有误了吗?
例如:
<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>
1个回答

8

closest方法找到的是最近的祖先元素,而不是DOM中的最近元素。在您的情况下,包含输入框的tr没有该类,因此选择器失败。您可能想要先找到最接近的tr,然后再找到具有该类的前一个兄弟元素。

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

感谢您的回答并快速提供解决方案! - Rokal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接