jQuery is a popular JavaScript library that is widely used for DOM manipulation and event handling in web development. One of the important concepts is the use of the this
keyword. In jQuery, this
represents the DOM element of the current operation, but in different contexts, the pointing of this
may be different. This article will analyze the usage skills of this
in jQuery through specific code examples.
First, let's look at a simple example:
<!DOCTYPE html> <html> <head> <title>Analysis of usage skills of this in jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button class="btn">点击我</button> <script> $('.btn').click(function() { console.log(this); }); </script> </body> </html>
In this example, when the button is clicked, the button element itself is output. In this case, this
refers to the DOM element that triggered the event, i.e. the button element itself.
Next, let’s look at a slightly more complex example:
<!DOCTYPE html> <html> <head> <title>Analysis of usage skills of this in jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="box"> <button class="btn">点击我</button> </div> <script> $('.box').click(function() { console.log(this); $('.btn', this).css('background-color', 'red'); }); </script> </body> </html>
In this example, when the div element wrapping the button is clicked, the div element itself will be output and the button's content will be changed. The background color is red. In this case, this
refers to the DOM element on which the event handler is registered, i.e. the div element that wraps the button.
In addition, another common situation is to use this
when traversing a collection of elements. For example:
<!DOCTYPE html> <html> <head> <title>Analysis of usage skills of this in jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <ul> <li>列表项1</li> <li>列表项2</li> <li>列表项3</li> </ul> <script> $('li').each(function() { console.log($(this).text()); }); </script> </body> </html>
In this example, all li elements are traversed through the each
method and their text content is output. In this case, this
refers to the currently traversed DOM element.
In general, the skills of using this
in jQuery are not difficult to master. The key is to understand that the direction of this
will change according to different contexts. Through continuous practice and practice, gradually mastering the usage skills of this
will help you write better jQuery code.
The above is the detailed content of Analysis of usage skills of this in jQuery. For more information, please follow other related articles on the PHP Chinese website!