Jquery's each function can be called cyclically using the element set obtained by the selector. This means that each time the passed function is executed, the this keyword in the function points to a different Dom element (each time it is a different matching element ). In addition, each time a function is executed, an element (INDEX) that represents the execution environment can be passed to the function ), the numeric value at the position in the matched element set is used as the parameter (an integer starting from scratch ).
I. Traversal
The following HTML is used as an example:
Reference <li> 0 </LI>
<Li> 1 </LI>
<Li> 2 </LI>
<Li> 3 </LI>
<Li> 4 </LI>
<Li> 5 </LI>
You can use the followingCodeSet the same CSS style for each Li:
Certificate ('li'apps.css ("border", "1px red solid ");
2. traverse an element
Jquery has the default iteration feature, but if you want to operate a qualified element in the iteration, you need to use the each function:
$ ('Lil'). Each (function (INDEX ){
If (Index = 2 | $ (this). ATTR ('id') = 'addclass') Then (this..css ("border", "1px red solid ");
});
3. terminate or skip a loop
Iteration is involved, which inevitably requires abnormal termination or force skipping. In jquery's each function, the following relationship exists:
Reference continue: Return true;
Break: Return false;
Directly returning will also jump out of jquery.
Therefore, you can write the following code:
$ ('Lil'). Each (function (INDEX ){
If (Index = 2) return true;
If (Index = 4) return false;
Certificate (this).css ("border", "1px red solid ");
});
here, 3rd and 5 Li elements are skipped without changing the CSS style.
(index starts from 0. You can also use other variable names)