You can select an element based on its position sequence. Based on the selection target, we can select one of the following filters for implementation-in jQuery we call it a "filter", although they look similar to CSS pseudo classes:: first matches the first element: last matches the last element: even matches an even index value
Requirement
Select an element in the order of its position.
Solution
Depending on the selection target, we can select one of the following filters for implementation-in jQuery we call it a "filter", although they look similar to the CSS pseudo class:
: First
Match the first element
: Last
Match the last element
: Even
Match All elements whose index values are even (the index value starts from 0)
: Odd
Match All elements with an odd index value (index value starts from 0)
: Eq (n)
Match the element whose index value is n
: Lt (n)
Match All elements whose index value is less than n
: Gt (n)
Match All elements whose index value is greater than n
The following HTML snippet is used as an example:
- First item
- Second item
- Third item
- Fourth item
There are several different ways to select the first element in the list:
JQuery ('ol li: first ');
JQuery ('ol li: eq (0 )');
JQuery ('ol li: lt (1 )');
Both the eq () and lt () filters accept a number as the parameter. Because the index value starts from 0, the index value of the first element is 0, the index value of the second element is 1.
Rendering rows in a table with different styles is a common requirement, which can be achieved using the even and odd filters. For the following table code:
0 |
Even |
1 |
Odd |
2 |
Even |
3 |
Odd |
4 |
Even |
You can add the class Attribute Based on the index value of the row in the table:
JQuery ('tr: even'). addClass ('even ');
To display the rendering effect, you need to define the corresponding class (even) in the CSS style sheet:
Table tr. even {
Background: # CCC;
}
Shows the final effect:
Discussion
As mentioned earlier, the index value of an element starts from 0. Except that the index value of the first element is 0, the use of the filter is very simple and clear. Another thing worth noting is that the filter needs to match the element set. The index value is meaningful only when the Element Set exists. Therefore, the following selector does not work:
JQuery (': even ');
In fact, the preceding statement can be executed, but this is because jQuery corrected the error when interpreting the selector. If the required element set is undefined, jQuery uses this element set as all elements in the document by default. Therefore, the preceding selector can actually work because it is exactly the same as the following selector:
JQuery ('*: even ');
However, in general, the element set on the left of the filter for matching is required. This element set can also be a defined jQuery object, for example:
JQuery ('ul li'). filter (': first ');
The filter method runs on a defined jQuery object (li set.