The use of $.each () in jquery

Source: Internet
Author: User

each () function is essentially a tool-class function provided by all frameworks, through which you can iterate over the property values of an object, an array, and handle it. Both jquery and jquery objects implement this method, and for jquery objects, simply delegate each method: The jquery object is passed as the first parameter to jquery's each method. In other words, The each method provided by jquery is a method call to each of the child elements in the object provided by the parameter one. The each method provided by the JQuery object is invoked on a child element within jquery.

The each function does not have exactly the same effect as the type of the parameter:

1. Traversing objects (with additional parameters)

Copy CodeThe code is as follows:
$.each (Object, function (P1, p2) {
This This here points to the current property value of the object in each traversal
P1;     P2; Accessing additional parameters
}, [' Parameter 1 ', ' parameter 2 ']);

2. Iterating through an array (with attachment parameters)

Copy CodeThe code is as follows:
$.each (Array, function (P1, p2) {
This This here points to the current element of the array in each traversal
P1;     P2; Accessing additional parameters
}, [' Parameter 1 ', ' parameter 2 ']);

3. Traversing objects (no additional parameters)

Copy CodeThe code is as follows:
$.each (Object, function (name, value) {
This This points to the value of the current property
Name Name indicates the current property of the object
Value Value that represents the current property of the object
});

4. Iterate through an array (no additional parameters)

Copy CodeThe code is as follows:
$.each (Array, function (i, value) {
This This points to the current element
I I represents the array current subscript
Value Value represents the current element of the array
});

Here are some common uses of each of the jquery methods

?
123456789101112131415161718192021 var arr = [ "one", "two", "three", "four"];    $.each(arr, function(){    alert(this);    });   //上面这个each输出的结果分别为:one,two,three,four      var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]   $.each(arr1, function(i, item){    alert(item[0]);   });   //其实arr1为一个二维数组,item相当于取每一个一维数组,   //item[0]相对于取每一个一维数组里的第一个值   //所以上面这个each输出分别为:1 4 7       var obj = { one:1, two:2, three:3, four:4};   $.each(obj, function(key, val) {    alert(obj[key]);     });   //这个each就有更厉害了,能循环每一个属性   //输出结果为:1 2 3 4

The each function in jquery is described in the official document of 1.3.2 as follows:

each (callback)

Executes a function with each matching element as the context.

means that each time the function passed in is executed, the This keyword in the function points to a different DOM element (each time a different matching element). Also, each time a function is executed, a function is passed a numeric value that represents the position of the element in the matching element collection as the execution environment (zero-based shaping). Returning ' false ' will stop the loop (just like using ' break ' in a normal loop). Return ' true ' to jump to the next loop (just like using ' continue ' in a normal loop).

The subsequent callback is a callback function that indicates the action to be given when traversing the element. Let's look at one of the following simple examples:
Iterate over two images and set their SRC properties. Note: Here this refers to a DOM object rather than a JQuery object.

HTML Code:

Copy CodeThe code is as follows:
jquery Code:
$ ("img"). each (function (i) {
THIS.SRC = "Test" + i + ". jpg";
});
Results: []
Of course, when iterating over the elements, jquery allows custom jumps, see the example code: You can use ' return ' to jump out of each () loop ahead of time.
HTML Code:
Copy CodeThe code is as follows:
<button>change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id= "Stop" >stop here</div>
<div></div>
<div></div>
<div></div>
JQuery Code:
Copy CodeThe code is as follows:
$ ("button"). Click (function () {
$ ("div"). each (function (Index,domele) {
$ (Domele). CSS ("backgroundcolor", "wheat");
if ($ (this). Is ("#stop")) {
$ ("span"). Text ("Where the div block is #" +index+ "stops.) ");
return false;
}
});
or write this:
Copy CodeThe code is as follows:
$ ("button"). Click (function () {
$ ("div"). each (function (index) {
$ (this). CSS ("backgroundcolor", "wheat");
if ($ (this). Is ("#stop")) {
$ ("span"). Text ("Where the div block is #" +index+ "stops.) ");
return false;
}
});
Graphic:


Each () method specifies the function to run for each matching element.

Tip: Return False to Stop the loop early.
Grammar
$ (selector). each (function (index,element)) parameter description
function (index,element) is required. A function that runs for each matching element.
? index-the index position of the selector
? element-the current element (you can also use the "this" selector

Instance
Output the text for each LI element:
Copy CodeThe code is as follows:
$ ("button"). Click (function () {
$ ("Li"). each (function () {
Alert ($ (this). Text ())
});
});
Instance
obj object is not an array
The biggest difference between this method and 1 is that the FN method will be carried out regardless of the return value. In other words, all properties of the Obj object will be called by the FN method, even if the FN function returns false. The call passed in with a parameter similar to 1.
Copy CodeThe code is as follows:
Jquery.each=function (obj, FN, args) {
if (args) {
if (obj.length = = undefined) {
for (var i in obj)
Fn.apply (obj, args);
}else{
for (var i = 0, ol = obj.length; i < ol; i++) {
if (fn.apply (obj, args) = = = False)
Break
}
}
} else {
if (obj.length = = undefined) {
for (var i in obj)
Fn.call (obj, I, obj);
}else{
for (var i = 0, ol = obj.length, val = obj[0]; I < ol && Fn.call (val,i,val)!== false; val = Obj[++i]) {}
}
}
return obj;
}
It is important to note that the specific invocation method of FN in each method is not a simple FN (i,val) or FN (args), but instead takes the form of Fn.call (Val,i,val) or fn.apply (Obj.args), which means that In the implementation of your own FN, you can use the this pointer to refer to an array or child elements of an object directly.

So how do you jump out of each?
jquery is more convenient when traversing selected objects. One application is to find the object that matches the condition inside, to jump out of this loop.
JavaScript jumps out of the loop in general.
Colleagues encountered this problem, subconsciously used the break, want to jump out of this cycle. Result error
Syntaxerror:unlabeled break must is inside loop or switch
After investigation, should use a
Return False in the callback function, most of the JQ methods are the same

Copy CodeThe code is as follows:
Returning ' false ' will stop the loop (just like using ' break ' in a normal loop).
Return ' true ' to jump to the next loop (just like using ' continue ' in a normal loop).

Articles you may be interested in:
    • Jquery.autocomplete implementation of Auto-complete function (detailed)
    • 12 Classic white-rich-jquery pictures Carousel plugin-front-end development essentials
    • How jquery dynamically adds and removes class style methods introduction
    • Summary of usage of $.get (), $.post (), $.ajax (), $.getjson () in jquery
    • JQuery Easyui API Chinese document-DataGrid data table
    • jquery triggers a Change event for a radio or checkbox
    • jquery Ajax two ways to submit form data
    • A summary of how to get ID values in jquery
    • JQuery Easyui API Chinese Document-ComboBox combo box
    • Mobile mobile app for jquery and HTML5 Canvas's lucky jackpot disc effect

Public search "Script House", select focus

Program Ape Things, send books and other activities waiting for you

    • Jquery
    • each
Related articles
  • jquery implements a method that restricts the number of characters entered into a textarea text box

    This article mainly introduced the jquery implementation limit textarea text box input character number method, involves the jquery keyboard event and the page element related operation skill, needs the friend can refer to the next 2015-05-05
  • jquery implementation of the navigation bar header menu item after click to change the color method

    This article mainly describes the implementation of jquery navigation bar header menu items to transform the color of the method, involving jquery in response to mouse events for page element traversal and property transformation related operation skills, need to refer to the friend of the 2017-07-07
  • Workarounds for JQuery Dollar symbol conflicts

    jquery dollar symbol conflict resolution, use jquery in conjunction with other JS libraries when you need to pay attention to the place. 2010-03-03
  • Easily learn jquery plugin Easyui Easyui Create RSS Feed reader

    This article is mainly to help you learn the jquery plugin Easyui, we will create an RSS reader through the jquery Easyui framework, interested in the small partners can refer to the 2015-11-11
  • jquery picture Carousel Implementation and encapsulation (i)

    This article is mainly for you to introduce the jquery picture Carousel Implementation and encapsulation, with a certain reference value, interested in small partners can refer to 2016-12-12
  • Replace the contents of a table and display the code for the progress bar based on jquery

    This example makes me more aware of how the rendering data is part of the front-end work, and how to make the values in the table into a clear bar chart? Listen to me, 2011-08-08 .
  • jquery implements a way to add lens magnification to a picture

    This article mainly introduces the jquery implementation of the image to add the lens magnification effect of the method, provides four kinds of magnifying glass effect for everyone to choose to use, and with complete source code, the need for friends can refer to the next 2015-06-06
  • 360-degree rotation of product images based on jquery circlr plugin

    CIRCLR is a product image can be a full 360-degree rotation display of the jquery plug-in, this article to you to share a circlr based on the jquery plug-in product image 360 degrees rotation, let's take a look at it 2015-09-09
  • jquery Implementation Dynamic Table Click Button Table Add a row

    Dynamic table, function for click Add button, table adds a row and give its Name property assigned value, click Delete, automatically delete this line, the specific implementation of the following 2014-08-08
  • jquery infinite cascading drop-down menu Simple example Demo

    This article mainly recommended to you a jquery infinite cascading drop-down menu Simple example demonstration, interested in the small partners can refer to 2015-11-11
Latest comments

What's interesting to you
    • 1How jquery Loads the page (page loads out
    • 2jquery to determine if the checkbox is selected for 3 kinds
    • 3 JQuery binds the Onchang of the Select tag
    • 4jquery Gets the value of the check box selected
    • 5jquery $ (document). Ready () and W
    • 6jquery Set the elements of disabled to ENA
    • 7A summary of how to get ID value in jquery
    • 8 jquery gets and modifies the SRC value of the IMG side
    • 9jquery.autocomplete for automatic completion
    • Ten How to use each () in jquery
What's recently updated
    • Juery resolving tablesorter Chinese sort and character range
    • jquery page plug-in jpaginate incompatibility problem in IE
    • The realization method of jquery graphic password
    • jquery implements the fade-out level two drop-down navigation menu
    • How jquery jumps to another page it's so easy
    • An example of the difference between prop and attr in jquery learning
    • A summary of common techniques used by jquery to manipulate tables
    • jquery to Div,span, A, button, radio
    • Learn the jquery Plugin Development menu Plugin from the start of practice
    • Jquery Implementation CheckBox Select All method
Sentient network brand server rental set think network VPS host Maple Letter technology IDC service providers commonly used online gadgets
    • CSS Code Tools
    • JavaScript Code formatting Tool
    • Online XML format/compression tool
    • PHP Code online Format Beautification tool
    • SQL code online Format beautification tool
    • Online HTML escape/Invert semantic tool
    • Online JSON code inspection/inspection/landscaping/formatting
    • JavaScript Regular online test tool
    • Generate QR Code tool online (enhanced version)
    • More Online tools

The use of $.each () in jquery

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.