Home >Web Front-end >JS Tutorial >Detailed explanation of the difference between $.each and $(selector).each() in JQuery

Detailed explanation of the difference between $.each and $(selector).each() in JQuery

巴扎黑
巴扎黑Original
2017-07-09 11:40:591410browse

PS: When I was writing the page at night, I discovered a problem. What are the differences between $.each and $(selector).each()? Baidu searches for keywords, and the homepage displays some previous experiences. Summarize them and post them.


1. $(selector).each()

jQuery traversal - each() method is mainly used for DOM traversal, each() method specifies execution for each matching element The function.

Syntax:


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

Displayed on W3SchoolCallback function is required, index - selector index position, element - the current element (the "this" selector can also be used).

$().each, this method is often used in DOM processing. If the page has multiple input tags of checkbox type, use $().each to process multiple checkbooks, for example:


$(“input[name=’ch’]”).each(function(i){    if($(this).attr(‘checked’)==true) {        //一些操作代码    }
})

The callback function can pass parameters , i is the traversal index.

2. Detailed introduction to each() of jquery

For the jQuery object, the each method is simply delegated: the jQuery object is used as the first A parameter is passed to jQuery's each method. In other words: the each method provided by jQuery calls the method one by one on all sub-elements of the object provided by parameter 1.

each() function is a tool function provided by basically all frameworks. Through it, you can traverse the attribute values ​​of objects and arrays and process them. 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. Traversing objects (with additional parameters):


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

2. Traverse the array (with attachment parameters):


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

3. Traverse the object (without additional parameters)


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

4. Traverse the array (no additional parameters)


1 $.each(Array, function(i, value) {2       this;      //this指向当前元素3       i;         //i表示Array当前下标4       value;     //value表示Array当前元素5  });6

The following are some commonly used methods of jQuery's each method Usage


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

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

each(callback )

Execute 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 (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:


##

1 <img/><img/>jQuery 代码: 
2 $("img").each(function(i){ 
3 this.src = "test" + i + ".jpg"; 
4 });
Result:[ , ]

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:


 1 <button>Change colors</button> 
 2 <span></span> 
 3 <p></p> 
 4 <p></p> 
 5 <p></p> 
 6 <p></p> 
 7 <p id="stop">Stop here</p> 
 8 <p></p> 
 9 <p></p> 
10 <p></p>
jQuery code:


1 $("button").click(function(){ 
2 $("p").each(function(index,domEle){ 
3 $(domEle).css("backgroundColor","wheat"); 
4 if($(this).is("#stop")){ 
5 $("span").text("在p块为#"+index+"的地方停止。"); 
6 return false; 
7 } 
8 });
Or write like this:


1 $("button").click(function(){ 
2 $("p").each(function(index){ 
3 $(this).css("backgroundColor","wheat"); 
4 if($(this).is("#stop")){ 
5 $("span").text("在p块为#"+index+"的地方停止。"); 
6 return false; 
7 } 
8 });
Illustration:

each() 方法规定为每个匹配元素规定运行的函数。

提示:返回 false 可用于及早停止循环。
语法
$(selector).each(function(index,element))参数 描述
function(index,element) 必需。为每个匹配元素规定运行的函数。
•index - 选择器的 index 位置
•element - 当前的元素(也可使用 "this" 选择器

实例
输出每个 li 元素的文本:


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

实例


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; 
}

需要特别注意的是each方法中fn的具体调用方法并不是采用简单的fn(i,val)或fn(args),而是采用了fn.call(val,i,val)或fn.apply(obj.args)的形式,这意味着,在你自己的fn的实现中,可以直接采用this指针引用数组或是对象的子元素。

那怎么跳出each呢
jquery再遍历选定的对象时候用each比较方便。有种应用是找到里面符合条件的对象后,要跳出这个循环。
javascript的跳出循环一般用break.
同事遇到这个问题,下意识 的用了break,想跳出这个循环。结果报错
SyntaxError: unlabeled break must be inside loop or switch
经查,应该用一个
在回调函数里return false即可,大多数jq的方法都是如此的


返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。 
返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。

该方法同1的最大区别是:fn方法会被逐次不考虑返回值的进行进行。换句话说,obj对象的所有属性都会被fn方法进行调用,即使fn函数返回false。调用传入的参数同1类似。

 

对于遍历一个数组,用$.each()来处理,简直爽到了极点。例如:


$.each([{“name”:”limeng”,”email”:”xfjylimeng”},{“name”:”hehe”,”email”:”xfjylimeng”},function(i,n)
{
alert(“索引:”+i,”对应值为:”+n.name);
});

参数i为遍历索引值,n为当前的遍历对象.

 


var arr1 = [ “one”, “two”, “three”, “four”, “five” ];
$.each(arr1, function(){
alert(this);
});
输出:one   two  three  four   fivevar arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:1   4   7var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});

输出:1 2 3 4 5

 

在jQuery里有一个each方法,用起来非常的爽,不用再像原来那样写for循环,jQuery源码里自己也有很多用到each方法。

其实jQuery里的each方法是通过js里的call方法来实现的。

下面简单介绍一下call方法。
call这个方法很奇妙,其实官方的说明是:“调用一个对象的一个方法,以另一个对象替换当前对象。”网上更多的解释是变换上下文环境,也有说是改变上下文this指针。
call([thisObj[,arg1[, arg2[,   [,.argN]]]]])

参数
thisObj
可选项。将被用作当前对象的对象。
arg1, arg2,  , argN
可选项。将被传递方法参数序列。
说明
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

引用网上有一个很经典的例子

Js代码:


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

用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4);
注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。

具体call更深入的就不在这里提了。

下面提一下jQuery的each方法的几种常用的用法

Js代码:


var arr = [ “one”, “two”, “three”, “four”];
$.each(arr, function(){
alert(this);
});//上面这个each输出的结果分别为:one,two,three,fourvar 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   7var obj = { one:1, two:2, three:3, four:4};
$.each(obj, function(key, val) {
alert(obj[key]);
});//这个each就有更厉害了,能循环每一个属性//输出结果为:1   2  3  4

暂时更新到这里

END

The above is the detailed content of Detailed explanation of the difference between $.each and $(selector).each() in JQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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