jquery $.each and $ (selector) The difference between each () is detailed

Source: Internet
Author: User

PS: in the evening when the page was written, a problem was found, $.each and $ (selector). What are the differences between each ()? Baidu search keywords, home show some predecessors experience, summed up, hair up.

1, $ (selector). each ()

The JQuery traversal-each () method is primarily used for DOM traversal, and each () method specifies the function to run for each matching element.

Grammar:

$ (selector). each (function (index,element))

It is necessary to display the callback function on the W3school, index-the index position of the selector, element-the current elements (you can also use the "this" selector).

$ (). Each, for this method, use more of the DOM processing. If the page has more than one input label type of checkbox, for this time use $ (). Each to process multiple checkbook, for example:

1 $ ("input[name= ' ch ']"). each (function(i) {2if($ (this). attr (' checked ') = =true)3{4/// Some operation code 5 6 }

A callback function is a parameter that can be passed, and I is the index of the traversal.

2, each of the jquery () detailed introduction

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.

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. Traverse the object (with additional parameters):

function (P1, p2) {      this;       // This here points to the current property value      of the object in each traversal P1; P2;     // Access additional Parameters }, [' Parameter 1 ', ' parameter 2 '

2. Iterate through the array (with attachment parameters):

function (P1, p2) {      this;       // This here points to the current element      of the array in each traversal P1; P2;     // Access additional Parameters }, [' Parameter 1 ', ' parameter 2 '

3. Traversing objects (no additional parameters)

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)

1 function (i, value) {2       this;      // This points to the current element 3       i;         // I represents the array current subscript 4       value;     // value represents the current element of the array 5  }); 6  

Here are some common uses of each of the jquery methods

1 vararr = ["One", "one", "three", "four"]; 2$.each (arr,function() {Alert ( This); });//The results for each of the above outputs are: One,two,three,four3 varARR1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]  4$.each (ARR1,function(I, Item)  {alert (item[0]); });//In fact, ARR1 is a two-dimensional array, item is equivalent to take each one-dimensional array,//item[0] relative to each one-dimensional array in the first value//So above this each output is: 1 4 75  varobj = {one:1, two:2, Three:3, Four:4}; 6$.each (obj,function(Key, Val)    {alert (Obj[key]); });//this each one is more powerful, can loop each property//output result is: 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:

1 2 $ ("img"). each (function3  this. src = "Test" + i + ". jpg"4

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:

1 2 3 4 5 6 7 8 9 Ten

JQuery Code:

 1  $ ("button"). Click (function   () { 2  $ ("div"). each ( function   (Index,domele) { 3  $ (domele). CSS (" BackgroundColor "," Wheat " 4  if  ($ ( this ). Is ("#stop"  5  $ ("span"). Text ("in Div block for #" +index+ "Place to stop. " 6  return   False  ;  7  }  8  }); 

or write this:

1$ ("button"). Click (function(){ 2$ ("div"). each (function(index) {3$( This). CSS ("backgroundcolor", "wheat"); 4 if($( This). Is ("#stop")){ 5$ ("span"). Text ("Where the div block is #" +index+ "stops.) "); 6 return false; 7 } 8});

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:

$ ("button"). Click (function() {$ ("Li"). each (function() {alert (

Instance

Jquery.each=function(obj, FN, args) {if(args) {if(Obj.length = =undefined) {  for(varIinchobj) fn.apply (obj, args); }Else{  for(vari = 0, ol = obj.length; I < ol; i++ ) { if(Fn.apply (obj, args) = = =false )  Break; } } } Else { if(Obj.length = =undefined) {  for(varIinchobj) fn.call (obj, I, obj); }Else{  for(vari = 0, ol = obj.length, val = obj[0]; I < ol && Fn.call (val,i,val)!==false; val = obj[++i]) {} }}returnobj;} 

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

Returns ' false ' to stop the loop (just like using ' break ' in a normal loop

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.

For traversing an array, using $.each () to deal with, it is absolutely cool to the extreme. For example:

$.each ([{"Name": "Limeng", "email": "Xfjylimeng"},{"name": "hehe", "email": "Xfjylimeng"},function(i,n) {Alert ("index:"+i, "corresponding value:" +N.name);});

Parameter i is the traversal index value, and n is the current traversal object.

var arr1 =function() {alert (this);}); Output: One   ,  three  four   fivevar arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9funct Ion(I, item) {alert (item[0]);}); Output:1   4   7var obj = {one:1, two:2, Three:3, Four:4, five:5function (Key, Val) {alert (Obj[key]);});

Output: 1 2 3 4 5

In jquery there is a each method, use it very cool, no longer like the original for The loop, jquery source itself has a lot to use each method.

In fact, the each method in jquery is implemented by the call method in JS.

Here's a quick introduction to the call method.
Call this method is wonderful, in fact, the official note is: "Invoke a method of an object, replace the current object with another object." "The explanation on the web is to transform the context, or to change the context of this pointer," he said.
Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])

Parameters
Thisobj
Options are available. The object that will be used as the current object.
Arg1, Arg2,, ArgN
Options are available. The method parameter sequence will be passed.
Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.

There is a classic example of a quote online

JS Code:

function Add (b) {alert (a+b);} function Sub (b) {alert (a-b);} Add.call (Sub,3,1);

Replace Sub,add.call (sub,3,1) = = Add (3,1) with add, so the result is: alert (4);
Note: The function in JS is actually an object, and the function name is a reference to a function object.

Specific call more in-depth is not mentioned here.

Here are some common uses of each of the jquery methods

JS Code:

vararr =["One", "one", "three", "Four "];$.each (arr,function() {alert ( This);});//The results for each of the above outputs are: One,two,three,fourvarARR1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]$.each (arr1,function(I, item) {Alert (item[0]);});//in fact, ARR1 is a two-dimensional array, item is equivalent to taking each one-dimensional array,//Item[0] Relative to the first value in each one-dimensional array//so the above each output is: 1 4 7varobj = {one:1, two:2, Three:3, Four:4};$.each (obj,function(Key, Val) {alert (Obj[key]);});//this each one is more powerful, can loop each property//the output is: 1 2 3 4

Temporarily updated to here

"END"

jquery $.each and $ (selector) The difference between each () is detailed

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.