This article mainly introduces the introduction of jQuery functions map () and each () and the Similarities and Differences analysis. If you need them, refer to the method Syntax: map ()
Map (callback)
Call the callback function for each element in the packaging set and collect the returned values to the jQuery object instance.
Parameters
The callback (function) callback function that calls this function for each element in the packaging set.
For example, the following code collects the id values of all p elements on the page into a javascript array:
The Code is as follows:
Var iDs = $ ("p"). map (function (){
Return (this. id = undefined )? Null: this. id;
}). Get ();
Let's look at a set of checkbox boxes in the following form:
The Code is as follows:
We can get a check box ID separated by commas:
The Code is as follows:
$ (': Checkbox'). map (function (){
Return this. id;
}). Get (). join ();
The result of this call is a string, "two, four, six ".
In the callback function, this points to the current DOM element in each iteration.
Method Syntax: each ()
Each (iterator)
Traverses all elements in the matching set and calls the passed iteration function for each element.
Iterator (function) callback function, called for each element in the matching set
The each () method can also be used to traverse javascript array objects or even a single object. For example:
The Code is as follows:
$ ([A, B, c, d]). each (function (){
Alert (this );
})
This statement calls an iteration function for each element of the Input $ () array. this in the function points to a separate array item.
During each callback function execution, the current number of cycles is passed as the parameter (counting starts from 0 ). More importantly, the callback function is triggered in the context where the current DOM element is the context. Therefore, the keyword "this" always points to this element.
Suppose there is such a simple unordered list on the page.
The Code is as follows:
You can select and iterate these lists:
The Code is as follows:
$ ("Li"). each (function (index ){
Console. log (index + ":" "+ $ (this). text ());
});
Each item in the list is displayed in the following message:
0: foo
1: bar
Differences between the two
The map () method is used to traverse operation arrays and objects. The each () method is used to traverse jquery objects.
Each () returns the original array and does not create a new array.
The map () method returns a new array. If map is used without any need, memory may be wasted.