使用jquery .each()函数时,在回调中使用Element参数的目的是什么? [英] What's the purpose of using an Element parameter in your callback when using the jquery .each() function?

查看:108
本文介绍了使用jquery .each()函数时,在回调中使用Element参数的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jquery中查看.each()函数的文档会显示以下方法签名:

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

.each( function(index, Element) )

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

我可以理解需要传递一个索引,以便可以在回调中使用它,但是如果您仅可以通过this关键字引用当前元素,为什么还要显式包括Element参数呢?是否只是为了让您可以指定您选择的实例名称?我的意思是,如果您仍然必须在jquery方法$()中包装一个命名实例来获取jquery对象,这与this完全不一样吗?文档似乎没有提到它在那里的原因.

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.

我认为这与闭包有关,但我不确定.看来,我所谓的命名实例"实际上是存储在回调范围内的变量中的数组中元素的本地副本或克隆.我怀疑通过使用this,它引用的变量就像是某种形式的闭包一样. @thecodeparadox在Firebug控制台中发现了一些让我思考的东西.还是不太清楚区别是什么,或者为什么您需要在数组中具有该元素的局部范围值.

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.

推荐答案

.this块的上下文经常会在.each块中更改,因此它们提供了对元素的引用,从而使您不必执行诸如"var that = this;"

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

这篇关于使用jquery .each()函数时,在回调中使用Element参数的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆