如果$(this)是nth-child(x)

Sai*_*ter 3 css jquery

我正在一个网站上工作,我遇到了一个问题.

我有一个12x24表使用nth-child(),我想使用jQuery来检查哪些nth-child()被点击.

目前我尝试过:

$('table.masteries tr.p0 td').click(function() {
    if($(this) == $('table.masteries tr.p0 td:nth-child(1)')) {
        console.log('true')
    }
});
Run Code Online (Sandbox Code Playgroud)

但我在控制台中没有得到任何回应.

该表格如下:

    <table class="masteries">
        <tr class="p0">
            <td></td>
...
        </tr>
        <tr class="p4">
            <td></td>
...
        </tr>
        <tr class="p8">
            <td></td>
...
        </tr>
        <tr class="p12">
            <td></td>
...
        </tr>
        <tr class="p16">
            <td></td>
...
        </tr>
        <tr class="p20">
            <td></td>
...
        </tr>
    <table>
Run Code Online (Sandbox Code Playgroud)

所以我想知道是否无法检查是否$(this)可以在if语句中工作.如果不是,是否有另一种方法来检查nth-child()jQuery/Javascript if-statements?

Sei*_*Sys 13

您可以使用jQuery的.index()方法查找当前元素具有的索引,或使用jQuery的.is()方法使用CSS选择器执行检查.

$('table.masteries tr.p0 td').click(function() {
    var $this = $(this);
    // You don't need to use these together, both should work independently
    if ($this.index() === 0 || $this.is(':nth-child(1)')) {
        console.log('true')
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 你可以只做`.is(':nth-​​child(1)')` - 不需要重复选择器的其余部分或传递jQuery集. (2认同)