【问题标题】:Get the second child of a jQuery element获取 jQuery 元素的第二个子元素
【发布时间】:2015-07-05 04:49:02
【问题描述】:

这个问题可能是重复的,但我没有发现任何有用的信息。

这是我的 sn-p:

$("table tbody tr").hover(

  function() {
    var secondCell = $(this).children[1].textContent;

    //secondCell.someCode
  },

  function() {
    //some code
  }

);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>foo</th>
      <th>foo</th>
      <th>foo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>bar</td>
      <td>bar</td>
      <td>bar</td>
    </tr>
  </tbody>
</table>

我想做的就是:当玩家悬停一行时,它应该提醒他们一条消息,并且该消息具有第二个单元格文本。
希望您能明白这一点,并在此先感谢您。

【问题讨论】:

  • $( "tr td:nth-child(2)" ) 应该成功了。

标签: jquery html this element


【解决方案1】:

有几种方法:

$( "tr td:nth-child(2)" )

$( "tr").children().eq(1)

$( "tr td").eq(1)

$( "tr td").filter(":nth-child(2)")

【讨论】:

  • 谢谢哈比比,但你知道,我想使用 $(this) 获取已选择行的单元格,无论如何,谢谢。
【解决方案2】:

在 jquery 中,.children() 是一个函数。因此,您需要先调用它,然后才能从数组中取出一个元素。查看jquery .children() 文档。

你可以这样使用它:jsfiddle

【讨论】:

  • 哦,是的,我看到了这个,但是当我输入它时,我的 IDE 说 children 不是一个函数,它是一个数组,但是当我尝试它时它起作用了。
【解决方案3】:

您也可以使用以下代码

$("table tbody tr").hover(

    function() {
        var secondCell = $(this).find("td:eq(1)").text();

        //secondCell.someCode
    },

    function() {
        //some code
    }

);

【讨论】:

    猜你喜欢
    • 2011-07-23
    • 2011-02-17
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多