What's the purpose of using an Element parameter in your callback when using the jquery .each() function?

北战南征 提交于 2019-12-21 21:00:02

问题


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.



来源:https://stackoverflow.com/questions/12415451/whats-the-purpose-of-using-an-element-parameter-in-your-callback-when-using-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!