获取jQuery元素的第二个子元素

时间:2015-07-05 04:49:03

标签: jquery html this element

这个问题可能会重复,但我找不到有用的东西 无论如何,这是我的HTML代码:

<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>

这是我的jQuery代码:

    $("table tbody tr").hover(

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

        //secondCell.someCode
    },

    function() {
        //some code
    }

);

我想做的就是:
当玩家徘徊一行时,它应该提醒他们一条消息并且该消息具有第二个单元格文本 希望你能得到这个想法,并提前感谢。

3 个答案:

答案 0 :(得分:3)

有几种方法:

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

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

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

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

答案 1 :(得分:0)

在jquery中,.children()函数。所以你需要先调用它才能从数组中获取一个元素。查看jquery .children()文档。

您可以像这样使用它:jsfiddle

答案 2 :(得分:0)

您也可以使用以下代码

$("table tbody tr").hover(

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

        //secondCell.someCode
    },

    function() {
        //some code
    }

);