【问题标题】:Get an element's parent td that is directly below a tr with a certain class获取一个元素的父 td,它位于某个类的 tr 正下方
【发布时间】:2016-03-24 12:47:53
【问题描述】:

我在网页中有一个复杂的表格结构,如下所示。表的嵌套可能更深。

我试图找到一个 jQuery 选择器来找到最接近给定输入元素的 td,并添加了这个 td 的 tr 应该有一个类 'class1' 的约束。

问题:如何借助 jQuery 获取我在上一段中描述的单个 'td`?我尝试了一些代码,但没有成功。

例如,如果给定的输入元素是firstname,那么紧接在这个元素周围的td 就不是我要找的了,但是带有<!--this is the td I am trying to get--> 注释的td 是正确的td。

我尝试使用选择器来获取这个 td,但它返回 6 个 td DOM 元素,而我只期望一个。你可以在这个 url 看到这个代码:demo for this scenario

我尝试过的代码不起作用

$('#firstName').parents("tr.class1").find("td");

嵌套表格的 HTML

<table>
   <tr class='class1'>
      <td>
         <!--some content here-->
      </td>
      <td><!--this is the td I am trying to get-->
         <table>
            <tr>
               <td>
                  First Name 
               </td>
               <td>
                  <input type='text' id='firstname'>  
               </td>
            </tr>
            <tr>
               <td>
                  Last Name 
               </td>
               <td>
                  <input type='text' id='lastname'>
               </td>
            </tr>
         </table>
      </td>
   </tr>
</table>

【问题讨论】:

    标签: jquery html jquery-selectors nested-table


    【解决方案1】:

    要达到您的要求,您需要将closest() 与直接子选择器&gt; 一起使用,以获取父td。试试这个:

    var $td = $('#firstname').closest('.class1 > td');
    

    Example fiddle

    【讨论】:

    • 所以给最接近的.class1 的值意味着该类中最接近firstname 的任何元素?
    • 是的。 closest() 向上遍历 DOM 以找到与提供的选择器匹配的最近的父元素。在这种情况下,它正在寻找一个td 元素,它是.class1 的直接后代。
    • 另外,.class1 &gt; td 似乎会直接在 class1 元素下找到所有 td 元素,但是由于您提到最接近 firstname ,所以我们得到了这两个最接近的 td 之一。
    • Also, it seems that .class1 &gt; td will find all td elements directly under class1 element 不,它只会得到单个td,它是#firstname 的父级,因为它只遍历DOM 树。它不考虑父母的任何兄弟姐妹。
    • 好的,明白了。它总是从给定的元素开始,向上爬上 DOM 树。
    猜你喜欢
    • 2017-10-16
    • 2018-05-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2012-08-30
    • 2012-07-10
    • 2013-04-29
    相关资源
    最近更新 更多