jquery这对$(这个)甚至可能是$ this [英] jquery this versus $(this) and maybe even $this
问题描述
我经常在jquery中看到使用关键字 this
的示例。有时我看到它与$和括号一起使用,有时没有。而且我以为我看到它与每个都有用。
I often see examples of using the keyword this
in jquery. Sometimes I see it used with the $ and parenthesis, other times without. And I thought I saw it used with a little of each.
所以,
var id = this.attr('id');
var id = $(this).attr('id');
var id = $this.attr('id');
这些都一样吗?有首选方式吗?是这个
一个javascript的东西和 $(this)
一个jQuery的东西?如果是这样, $这个
在哪里下跌?
Are these all the same? Is there a preferred way? Is this
a javascript thing and $(this)
a jQuery thing? If so, where does $this
fall?
我知道这可能是一个全新的问题,但是我没有能够得到简单的,这个
本身就可以了。我只能 $(this)
才能工作。我不确定我做错了什么,或者我是否一直在阅读错别字的例子。
I know this is probably a total newbie question, but I haven't been able to get the simple, this
, by itself, to work. I can only get $(this)
to work. I'm not sure if I'm doing something wrong, or if I've been reading examples with typos.
推荐答案
这个
是一个JavaScript的东西。它指的是函数运行的上下文。对于大多数事件处理程序,它是正在侦听事件的(原始)DOM元素。在其他情况下,它将意味着其他事情;谷歌搜索这个
在JavaScript中可能具有启发性。
this
is a JavaScript thing. It refers to the "context" a function is running in. For most event handlers, it is the ("raw") DOM element that is listening to an event. In other situations it will mean other things; Googling "this
in JavaScript" might be enlightening.
I说它是原始DOM元素,因为jQuery通常用于在jQuery包装器中包装普通DOM元素,因此你可以使用jQuery方法,如 attr
而不是通常的( getAttribute
, setAttribute
等)。这个包装是通过 $
函数完成的,你可以在那里看到 $(this)
。例如:
I say it is the "raw" DOM element because jQuery is often used to wrap plain DOM elements in a jQuery wrapper, so you can use jQuery methods like attr
instead of the usual ones (getAttribute
, setAttribute
, etc.). This wrapping is accomplished with the $
function, and that's where you see $(this)
. For example:
this.getAttribute("href")
/* or */ someElement.getAttribute("href")
与
$(this).attr("href")
/* or */ $(someElement).attr("href")
$ this
或这个$
只是一个变量名。但是,通常做一个像
$this
or this$
is just a variable name. But, it is often conventional to do an assignment like
var $this = $(this);
这样做的原因是为了避免不断调用 $
function,这有点贵,因为它每次都会创建一个新的jQuery包装器对象。如果将包装元素存储在变量中,则效率会稍微提高。
The reason for this is to avoid continually invoking the $
function, which is somewhat expensive as it creates a new jQuery wrapper object every time. If you store the wrapped element in a variable, you gain slightly in efficiency.
在极少数情况下,这个
可能已经是一个jQuery包装器了。经常出现的情况是编写jQuery插件时。在这种情况下,您可以直接执行 this.attr(id)
之类的操作,而无需先将其包装起来,因为它已经被包装。在通常情况下(事件处理程序, $。每个
等),包装器是必需的。
In rare cases, this
might already be a jQuery wrapper. The case that comes up often for me is when writing jQuery plugins. In that case you can do things like this.attr("id")
directly, without wrapping it up first, because it's already wrapped. In the usual cases (event handlers, $.each
, etc.) the wrapper is necessary.
这篇关于jquery这对$(这个)甚至可能是$ this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!