What's the purpose of using an Element paramet

2020-07-25 10:51发布

问题:

Looking at the docs for the .each() function in jquery shows the following method signature:

.each( function(index, Element) )

http://api.jquery.com/each/

I can understand needing to pass in an index so that it is available for use within the callback but why would you explicitly include the Element parameter if you can just reference the current element by the this keyword? Is it there just so that you can specify an instance name of your choice? I mean, if you still have to wrap a named instance in the jquery method $() to get back a jquery object isn't that exactly the same as this? The docs don't seem to mention why it is there.

Update:

I think this has something to do with closures but I'm not sure. It seems like what I'm referring to as a "named instance" is actually a local copy or clone of the element in the array stored in a variable within the scope of the callback. I suspect that by using this it is referencing a variable as if it were some sort of closure. @thecodeparadox found something in a firebug console that got me thinking about this. Still not quite sure what the difference is though or why you would ever need to have a locally scoped value of the element in the array.

回答1:

the context of "this" can change often inside a .each block so they provide a reference to the element saving you from having to do something like "var that = this;"



回答2:

Element refers to the each element of Object on which loop happen. Within the callback function you can also get that each value using this also.

For example:

$(['a','b', 'c']).each(function(i, el) {
  console.log(el);
  console.log(this); 
});

One thing that I found

For above example if you see the console.log(el) you will get the result:

a, b, c..

but if you see the console.log(this) you will see String object.

To get the output same as console.log(el) you need to write console.log( this[0] ).

That means to get the original value directly el i.e. callback parameter is reliable and easy.

Open the firebug and see output.