jQuery:“$(this)”和“this”的区别是什么?

时间:2022-08-23 11:29:43

I am currently working through this tutorial: Getting Started with jQuery

我现在正在学习这个教程:开始使用jQuery。

For the two examples below:

对于以下两个例子:

$("#orderedlist").find("li").each(function (i) {
    $(this).append(" BAM! " + i);
});
$("#reset").click(function () {
    $("form").each(function () {
        this.reset();
    });
});

Notice in the first example, we use $(this) to append some text inside of each li element. In the second example we use this directly when resetting the form.

注意,在第一个示例中,我们使用$(this)在每个li元素中附加一些文本。在第二个示例中,我们在重新设置表单时直接使用它。

$(this) seems to be used a lot more often than this.

$(this)似乎比这个更常用。

My guess is in the first example, $() is converting each li element into a jQuery object which understands the append() function whereas in the second example reset() can be called directly on the form.

我的猜测是在第一个示例中,$()将每个li元素转换成一个jQuery对象,该对象理解append()函数,而在第二个示例reset()中可以直接调用表单。

Basically we need $() for special jQuery-only functions.

基本上,我们需要$()用于特殊的jquery函数。

Is this correct?

这是正确的吗?

7 个解决方案

#1


461  

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

是的,当您使用jQuery时,您只需要$()。如果您想要jQuery的帮助来做DOM的事情,请记住这一点。

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

基本上每次你得到一组元素后,jQuery就会把它变成一个jQuery对象。如果你知道你只有一个结果,它就会在第一个元素中。

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

等等……

#2


348  

$() is the jQuery constructor function.

$()是jQuery构造函数。

this is a reference to the DOM element of invocation.

这是对调用的DOM元素的引用。

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

基本上,在$(this)中,您只是将这个$()作为一个参数传递,这样您就可以调用jQuery方法和函数。

#3


84  

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.

是的,您需要$(this)用于jQuery函数,但是当您想要访问不使用jQuery的元素的基本javascript方法时,您可以使用它。

#4


64  

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:

在使用jQuery时,建议通常使用$(this)。但是,如果你知道(你应该学习和知道)区别,有时候使用它会更加方便和快捷。例如:

$(".myCheckboxes").change(function(){ 
    if(this.checked) 
       alert("checked"); 
});

is easier and purer than

是否比?

$(".myCheckboxes").change(function(){ 
      if($(this).is(":checked")) 
         alert("checked"); 
});

#5


41  

this is the element, $(this) is the jQuery object constructed with that element

这是元素,$(this)是用该元素构造的jQuery对象。

$(".class").each(function(){
 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);
});

A deeper look

一个更深层次的看

thisMDN is contained in an execution context

这个mdn包含在执行上下文中。

The scope refers to the current Execution ContextECMA. In order to understand this, it is important to understand the way execution contexts operate in JavaScript.

范围是指当前执行的ContextECMA。为了理解这一点,理解JavaScript中执行上下文的操作方式是很重要的。

execution contexts bind this

执行上下文绑定这

When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this occurs.

当控制进入执行上下文(范围)的代码被执行在环境变量设置(词汇和变量环境——实际上这设置变量进入这一领域已经访问,以及局部变量存储区域),和绑定。

jQuery binds this

jQuery结合这

Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using applyMDN.

执行上下文形成一个逻辑堆栈。结果是,在堆栈中更深入的上下文可以访问以前的变量,但是它们的绑定可能已经被修改了。每次jQuery调用一个回调函数时,它都会使用applyMDN来改变这个绑定。

callback.apply( obj[ i ] )//where obj[i] is the current element

The result of calling apply is that inside of jQuery callback functions, this refers to the current element being used by the callback function.

调用应用程序的结果是jQuery回调函数内部,这是指回调函数使用的当前元素。

For example, in .each, the callback function commonly used allows for .each(function(index,element){/*scope*/}). In that scope, this == element is true.

例如,在.each中,通常使用的回调函数允许。each(函数(index,element){/*scope*/})。在这个范围内,这个==元素为真。

jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.

jQuery回调函数使用apply函数来绑定当前元素调用的函数。这个元素来自jQuery对象的元素数组。所构造的每个jQuery对象都包含一个元素数组,这些元素与用来实例化jQuery对象的selectorjQuery API相匹配。

$(selector) calls the jQuery function (remember that $ is a reference to jQuery, code: window.jQuery = window.$ = jQuery;). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $() internally uses new jQuery(). Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this).

$(选择器)调用jQuery函数(记住$是对jQuery的引用,代码:window)。jQuery =窗口。= jQuery;美元)。在内部,jQuery函数实例化一个函数对象。因此,虽然它可能不是显而易见的,但使用$()内部使用新的jQuery()。这个jQuery对象的部分构造是找到选择器的所有匹配项。构造函数还将接受html字符串和元素。当您将此传递给jQuery构造函数时,您将传递一个jQuery对象的当前元素。然后,jQuery对象包含与选择器匹配的DOM元素的类似数组的结构(或者在这个例子中只有一个元素)。

Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this to the current element. This call can be seen in the code snippet above where obj is the array-like structure, and i is the iterator used for the position in the array of the current element.

一旦jQuery对象被构建,jQuery API就会被公开。当调用jQuery api函数时,它会在内部迭代这个arraylike结构。对于数组中的每个项目,它调用api的回调函数,将回调函数绑定到当前元素。这个调用可以在上面的代码片段中看到,obj是arraylike结构,而i是用于当前元素数组中位置的迭代器。

#6


36  

Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.

是的,通过使用$(this),您可以为对象启用jQuery功能。通过使用它,它只有通用的Javascript功能。

#7


-2  

this reference a javascript object and $(this) used to encapsulate with jQuery.

这个引用一个javascript对象和$(this)用来封装jQuery。

Example =>

示例= >

// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')

// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)

// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()

//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()

//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value

or 

this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')

#1


461  

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

是的,当您使用jQuery时,您只需要$()。如果您想要jQuery的帮助来做DOM的事情,请记住这一点。

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

基本上每次你得到一组元素后,jQuery就会把它变成一个jQuery对象。如果你知道你只有一个结果,它就会在第一个元素中。

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

等等……

#2


348  

$() is the jQuery constructor function.

$()是jQuery构造函数。

this is a reference to the DOM element of invocation.

这是对调用的DOM元素的引用。

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

基本上,在$(this)中,您只是将这个$()作为一个参数传递,这样您就可以调用jQuery方法和函数。

#3


84  

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.

是的,您需要$(this)用于jQuery函数,但是当您想要访问不使用jQuery的元素的基本javascript方法时,您可以使用它。

#4


64  

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:

在使用jQuery时,建议通常使用$(this)。但是,如果你知道(你应该学习和知道)区别,有时候使用它会更加方便和快捷。例如:

$(".myCheckboxes").change(function(){ 
    if(this.checked) 
       alert("checked"); 
});

is easier and purer than

是否比?

$(".myCheckboxes").change(function(){ 
      if($(this).is(":checked")) 
         alert("checked"); 
});

#5


41  

this is the element, $(this) is the jQuery object constructed with that element

这是元素,$(this)是用该元素构造的jQuery对象。

$(".class").each(function(){
 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);
});

A deeper look

一个更深层次的看

thisMDN is contained in an execution context

这个mdn包含在执行上下文中。

The scope refers to the current Execution ContextECMA. In order to understand this, it is important to understand the way execution contexts operate in JavaScript.

范围是指当前执行的ContextECMA。为了理解这一点,理解JavaScript中执行上下文的操作方式是很重要的。

execution contexts bind this

执行上下文绑定这

When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this occurs.

当控制进入执行上下文(范围)的代码被执行在环境变量设置(词汇和变量环境——实际上这设置变量进入这一领域已经访问,以及局部变量存储区域),和绑定。

jQuery binds this

jQuery结合这

Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using applyMDN.

执行上下文形成一个逻辑堆栈。结果是,在堆栈中更深入的上下文可以访问以前的变量,但是它们的绑定可能已经被修改了。每次jQuery调用一个回调函数时,它都会使用applyMDN来改变这个绑定。

callback.apply( obj[ i ] )//where obj[i] is the current element

The result of calling apply is that inside of jQuery callback functions, this refers to the current element being used by the callback function.

调用应用程序的结果是jQuery回调函数内部,这是指回调函数使用的当前元素。

For example, in .each, the callback function commonly used allows for .each(function(index,element){/*scope*/}). In that scope, this == element is true.

例如,在.each中,通常使用的回调函数允许。each(函数(index,element){/*scope*/})。在这个范围内,这个==元素为真。

jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.

jQuery回调函数使用apply函数来绑定当前元素调用的函数。这个元素来自jQuery对象的元素数组。所构造的每个jQuery对象都包含一个元素数组,这些元素与用来实例化jQuery对象的selectorjQuery API相匹配。

$(selector) calls the jQuery function (remember that $ is a reference to jQuery, code: window.jQuery = window.$ = jQuery;). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $() internally uses new jQuery(). Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this).

$(选择器)调用jQuery函数(记住$是对jQuery的引用,代码:window)。jQuery =窗口。= jQuery;美元)。在内部,jQuery函数实例化一个函数对象。因此,虽然它可能不是显而易见的,但使用$()内部使用新的jQuery()。这个jQuery对象的部分构造是找到选择器的所有匹配项。构造函数还将接受html字符串和元素。当您将此传递给jQuery构造函数时,您将传递一个jQuery对象的当前元素。然后,jQuery对象包含与选择器匹配的DOM元素的类似数组的结构(或者在这个例子中只有一个元素)。

Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this to the current element. This call can be seen in the code snippet above where obj is the array-like structure, and i is the iterator used for the position in the array of the current element.

一旦jQuery对象被构建,jQuery API就会被公开。当调用jQuery api函数时,它会在内部迭代这个arraylike结构。对于数组中的每个项目,它调用api的回调函数,将回调函数绑定到当前元素。这个调用可以在上面的代码片段中看到,obj是arraylike结构,而i是用于当前元素数组中位置的迭代器。

#6


36  

Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.

是的,通过使用$(this),您可以为对象启用jQuery功能。通过使用它,它只有通用的Javascript功能。

#7


-2  

this reference a javascript object and $(this) used to encapsulate with jQuery.

这个引用一个javascript对象和$(this)用来封装jQuery。

Example =>

示例= >

// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')

// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)

// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()

//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()

//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value

or 

this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')