Use continue and break in jquery's each () function

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.