:nth-child(even)
and :even
in jquery are looking similar but selecting different element开发者_如何学编程s. Please let me know the differences.
Happy Coding...
Here is an example to illustrate the difference:
http://jsfiddle.net/bEfT6/
:even
matches every 2nd element within the set of elements you are selecting. Where as :nth-child(even)
matches any elements which are an even numbered child of their respective parent.
So in the example, you see that the two selectors affect different elements. The elements with red text match the selected class and are even numbered children of the parent div. The ones with blue background match the selected class and are even within that selection.
So:
.something:nth-child(odd)
matches every element with the class something
which is an even child of it's parent.
.something:even
matches every other element with the class something
. (regardless of relation to its siblings)
:even
is 0-based, while :nth-child
is 1-based. This is from the docs for :even
In particular, note that the 0-based indexing means that, counter-intuitively, :even selects the first element, third element, and so on within the matched set.
This is for :nth-child
Because jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript's "0-indexed" counting.
精彩评论