Home > Web Front-end > JS Tutorial > Instructions for using each() in JQuery

Instructions for using each() in JQuery

巴扎黑
Release: 2017-07-09 11:10:09
Original
1138 people have browsed it

For the jQuery object, the each method is simply delegated: the jQuery object is passed as the first parameter to jQuery's each method. In other words: the each method provided by jQuery is for the object provided by parameter one. All sub-elements in the method are called one by one.

Theeach() function is a tool function provided by basically all frameworks. Through it, you cantraverse objects and arrays. attribute value and process it. Both jQuery and jQuery objects implement this method. For jQuery objects, the each method is simply delegated: the jQuery object is passed as the first parameter to jQuery's each method. In other words: the each method provided by jQuery is All sub-elements in the object provided by parameter 1 are called one by one. The each method provided by the jQuery object calls the sub-elements inside jQuery one by one.

The effect of each function is not completely consistent depending on the type of parameters:

1. Traverse the object (with additional parameters)

The code is as follows:

$.each(Object, function(p1, p2) {
     this;       //这里的this指向每次遍历中Object的当前属性值
     p1; p2;     //访问附加参数
}, ['参数1', '参数2']);
Copy after login

2, Traverse the array(with attachment parameters)

The code is as follows:

$.each(Array, function(p1, p2){
     this;       //这里的this指向每次遍历中Array的当前元素
     p1; p2;     //访问附加参数
}, ['参数1', '参数2']);
Copy after login

3, Traverse the object (No additional parameters)

The code is as follows:

$.each(Object, function(name, value) {
     this;      //this指向当前属性的值
     name;      //name表示Object当前属性的名称
     value;     //value表示Object当前属性的值
});
Copy after login

4. Traverse the array (no additional parameters)

The code is as follows:

$.each(Array, function(i, value) {
     this;      //this指向当前元素
     i;         //i表示Array当前下标
     value;     //value表示Array当前元素
});
Copy after login

The following are some common uses of jQuery's each method


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
Copy after login

The each function in JQuery is in 1.3.2 The description in the official documentation is as follows:

each(callback)

Execute a function using 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 (a different matching element each time). Moreover, every time the function is executed, a numeric value representing the position of the element as the execution environment in the set of matching elements is passed to the function as a parameter (an integer starting from zero). Returning 'false' will stop the loop (just like using 'break' in a normal loop). Returns 'true' to jump to the next loop (just like using 'continue' in a normal loop).

The following callback is the callback function, indicating the operation that should be given when traversing the elements. Let’s look at a simple example below:
Iterate over two images and set their src attributes. Note: here this refers to the DOM object rather than the jQuery object.

HTML code:

The code is as follows:

<img/><img/>jQuery 代码: 
$("img").each(function(i){ 
this.src = "test" + i + ".jpg"; 
});
Copy after login


Result:[ , < img src="test1.jpg" /> ]
Of course, jquery allows customized jumps when traversing elements. Please see the sample code: you can use 'return' to jump out of the each() loop in advance.
HTML code:

The code is as follows:

<button>Change colors</button> 
<span></span> 
<p></p> 
<p></p> 
<p></p> 
<p></p> 
<p id="stop">Stop here</p> 
<p></p> 
<p></p> 
<p></p>
Copy after login


jQuery code:

The code is as follows:

$("button").click(function(){ 
$("p").each(function(index,domEle){ 
$(domEle).css("
background
Color","wheat"); 
if($(this).is("#stop")){ 
$("span").text("在p块为#"+index+"的地方停止。"); 
return false; 
} 
});
Copy after login


Or write like this:

The code is as follows:

$("button").click(function(){ 
$("p").each(function(index){ 
$(this).css("backgroundColor","wheat"); 
if($(this).is("#stop")){ 
$("span").text("在p块为#"+index+"的地方停止。"); 
return false; 
} 
});
Copy after login


Illustration:


each() method is specified for each Matching elements specify a function to run.

Tip: Returning false can be used to stop the loop early.
Syntax
$(selector).each(function(index,element)) Parameter Description
function(index,element) Required. Specifies the function to run for each matching element.
•index - the index position of the selector
•element - the current element (you can also use the "this" selector

Example
Output the text of each li element:

Copy code The code is as follows:


$("button").click(function(){
$("li").each (function(){
alert($(this).text())
});
});


Example
The obj object is not an array
The biggest difference between this method and 1 is that the fn method will be executed one after another without considering the return value. In other words, all properties of the obj object will be called by the fn method, even if fn is used. The function returns false. The parameters passed in are similar to 1.

##Copy code The 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 should be noted that the specific calling method of fn in each method is not simple fn(i,val) or fn(args), but fn.call(val,i,val) Or in the form of fn.apply(obj.args), which means that in your own implementation of fn, you can directly use this pointer to reference the sub-elements of the array or object.

How to jump out of each?
It is more convenient to use each when jquery traverses the selected object. There is an application that needs to break out of this loop after finding an object that meets the conditions.
To break out of a loop in JavaScript, break is generally used.
When a colleague encountered this problem, he subconsciously used break to get out of the loop. The result is an error
SyntaxError: unlabeled break must be inside loop or switch
After investigation, you should use a
to return false in the callback function. Most jq methods are like this

Copy code The 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).

The above is the detailed content of Instructions for using each() in JQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template