1. It is estimated that many people will use the each method in jQuery.
Then let’s take a look at what jQuery has done.
Find the source code of each in jquery:
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i ], args ) = == false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i ] ) === false ) {
break;
}
}
}
}
return object;
},
this code It’s relatively simple, there should be no problem.
In order to test this thing, I wrote the following js;
$.each($(".demo"),function(){
console.log("show");
});
Then add a piece of html:
Then I took the jQuery source code to debug, thinking I could get the correct results. But it's a pity.
As you can see, the object here is not the three html objects I want, but the 8 built-in data types of js. After
, I added a piece of code to the jquery source code:
console.log(Object.prototype.toString(object));
console.log(length);
The input after
is as follows:
That is to say, when the document is loaded, jQuery will use each to traverse the dom object, even if it is not used
$(function(){
});
After traversing the specified object, bubbling will still continue to traverse the parent element.
2. Use callback function parameters according to jQuery source code
$.each($(".demo"),function(a,b){
console.log(a "" $(a).attr("class"));
} )
You can see from the source code:
callback.call( object[ i ], i, object[ i ] )
Finally, the current object is passed to the callback function through the call method, then you can go as above Use properties from the current object. Of course, you can also call it directly using this.
If we talk about more complicated things, for example, here I pass $(".demo") as object to $.each()
Sometimes it is not passed jQuery or html object. But an Object or array.
And there are many other objects or methods in the array.
This way you can get more effects.
3. Use call or apply to implement callback mode.
As you can see from the above code:
callback.call(obj,args)
callback.apply([obj],args)
, you only need to pass the callback function to call it yourself, which is very useful for improving the reuse of the code.
But there are also some shortcomings, such as reduced code readability, increased coupling, etc.
If you get something occasionally, record it to prevent forgetting!