$('table td:eq(2) a')
return the a
tag of the third column but only from the fir开发者_StackOverflow中文版st row.
Why?
It is not a bug but it is definitely confusing. What will give you the result you expect is:
$('table td:nth-child(3) a')
While :nth-child and :eq seem very similar the behavior can be quite different as can be seen from the result you expected.
The jQuery documentation on this can be found here. It states:
The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the nth one is selected.
In simpler words, eq(2) will select the third element in the while result set while :nth-child(3) will select the 3 child of its parent. And in this case the parent will be its tr.
No, it's not a bug. It matches the anchor tag in third element in the set matched by table td
, so it's in the third cell in the table.
(If the table was only two cells wide, you would get the first cell in the second row.)
In simple word,
According to your code $('table td:eq(2)')
returns third td
in table
as strting from index=0 it will pick third td
see below
for $('table td:eq(4)')
result would be fifth td
of the table see below
to select whole second column use :nth-child() index starts from 1
ex: $('table td:nth-child(2)')
I hope you get your answer.
$('table td:eq(2)')
will select all 'table td'
, and the index eq(2)
will select the third td
from this collection. so there is just one a
under third column.
精彩评论