$.each: This method is used to iterate through any collection, including arrays and objects
$(selector).each: This method is used to traverse Jquery objects
Syntax: $.each(obj,callback,args)
①Transfer through the array
var arr = ["a","b","c","d",…];
$.each(arry,function(index,value){…})
In the callback function: index represents the index of the array, value represents the value in the array
②Transfer Json objects
var json = {key1:value1, key2:value2, key3:value3}
$.each(json, function(key,value){…})
In the callback function: key represents the key in the json object, value represents the value in the json object
③Traveling through Jquery objects
var doms = $("div");//Jquery object itself is a collection, and Jquery object can be converted into Dom object through indexing
$.each(doms, function(index,value){..})
In the callback function: index represents the index in the Jquery object, value represents the dom object in the Jquery object, and the same dom object can also be obtained through this
There is another way to write ③, which is $("div").each(function(index,value){…})
For the $.each method, you can exit the loop by returning false in the callback function. If return true, it is equivalent to the continue in the for loop
Question: Why is this in the $().each callback function not a Jquery object but a Dom object
Since the essence of the $().each method is implemented by calling $.each, we can see the code calledback.apply(object[i++],args) by analyzing the $.each source code.
For the object passed in $().each, the object[i++] converts the Jquery object into a dom object, and then hijacks the object's characteristics according to the apply method, then this in the callback function is changed to a dom object
We often see this writing method in the Jquery plug-in. Through the above analysis, I think I should understand it
$.fn.test = function(option){return this.each(function(){//This is a Jquery object alert(this);//and this is a Dom object})}The above article has a deep understanding of $.each and $(selector).each is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.