如何使用jQuery查找最近的表格

3

我想在搜索值时获取最接近的表格。

这是我的代码,但我总是得到“undefined”。

jQuery:

 $(function() {
     $("#searchValue").keyup(function() {
         alert($(this).closest('table').attr('id'));
     });
 });

HTML:

<input type='text' name='searchValue' id='searchValue'/>

<table id='tablePlanning' class='tablesorter'>
    <thead>
        <tr>
            <th>PR Code</th>
            <th>Klant</th>
            <th>Description</th>
            <th>Project status</th>
            <th>Project Leader</th>
            <th>Coordinator</th>
            <th>Account manager</th>
            <th>Billing</th>
            <th>Start Datum</th>
            <th>Hardware</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

8
请分享您相关的HTML代码... - A. Wolff
要使用 closest,您的表格应该是 #searchValue 的一个 parent - Ricardo Binns
3
假设$("#searchValue")位于一个<table>元素内部,我唯一能想到的解释是,该表格没有设置id属性。 - Barney
1
您的输入不在表格内,因此无法使用closest。为什么不直接使用.next('table')siblings('table')$('#tablePlanning') - putvande
回想起来,也许closest()并不是一个迭代祖先的最合适的方法名称... - Frédéric Hamidi
1个回答

4
尝试使用.next()来查找以下table(在相同的DOM级别):
$(function() {
   $("#searchValue").keyup(function() {
     alert($(this).next('table').attr('id'));
   });
});

.closest() 是用来查找元素的第一个父级元素。

但是,由于您的表格有一个 id,因此您应该使用它(我希望您没有几个具有 #tablePlanning id 的表格,否则,您应该使用类名。


2
具体来说,closest() 匹配祖先链中与选择器匹配的第一个元素,包括源元素本身 - Frédéric Hamidi

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