Distinguishing between '$(this)' and 'this' in jQuery
While working through the jQuery Getting Started tutorial, you encountered a subtle difference between using '$(this)' and 'this' directly. In the code samples you provided:
$("#orderedlist").find("li").each(function (i) { $(this).append(" BAM! " + i); }); $("#reset").click(function () { $("form").each(function () { this.reset(); }); });
You correctly deduced that the key distinction lies in the jQuery-specific functionality.
'$(this)' for jQuery Operations
In the first example, '$(this)' is used within the 'each' function to iterate over the 'li' elements. By encapsulating 'this' within '$(this)', you are converting it into a jQuery object. This allows you to use jQuery methods like 'append' to manipulate the elements directly.
'this' for Non-jQuery Functions
In the second example, 'this' is used within the click handler function for the reset button. Here, you are targeting the 'form' element. Resetting a form is a standard HTML feature that does not require jQuery intervention. Hence, you can call 'reset' directly on 'this'.
When to Use Each Form
As a general rule, whenever you want to perform jQuery-specific operations on elements, use '$(this)'. This ensures that the element is encapsulated as a jQuery object and gives you access to its full capabilities. For non-jQuery operations like resetting a form, you can use 'this' directly.
Remembering the Relationship
To simplify matters, keep in mind the following equivalency:
$(this)[0] === this
This means that you can access the original DOM element at any time by indexing the jQuery object with '[0]'.
The above is the detailed content of When Should I Use `$(this)` vs. `this` in jQuery?. For more information, please follow other related articles on the PHP Chinese website!