Home >Web Front-end >JS Tutorial >Parse the pointer of this in the click event in jQuery
The pointing of this in the click event in jQuery is a problem that often confuses beginners. In jQuery, this usually refers to the element currently being processed, but in a click event, this will point differently. This article will analyze in detail the point of this in the click event in jQuery, and attach specific code examples.
In jQuery, various events can be bound to elements by using the event binding method. The most common one is the click event. When the user clicks on an element, the click event will be triggered, and this will point to the element that triggered the event. However, things are not always that simple, and where this points in a click event may be affected by other factors.
Here is a simple sample code:
<!DOCTYPE html> <html> <head> <title>jQuery中this在点击事件中的指向</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button class="btn">按钮1</button> <button class="btn">按钮2</button> <script> $('.btn').click(function() { console.log($(this).text()); }); </script> </body> </html>
In the above code, we have two buttons, both of which have the same class name "btn". When any button is clicked, the click event will be triggered, and the console will output the text content of the clicked button. In this example, this points to the button element itself that triggered the click event, so you can get the jQuery object of the current button through $(this), and then get the text content of the button through the .text() method.
If we modify the code slightly:
<!DOCTYPE html> <html> <head> <title>jQuery中this在点击事件中的指向</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div> <button class="btn">按钮1</button> <button class="btn">按钮2</button> </div> <script> $('.btn').click(function() { console.log($(this).parent().text()); }); </script> </body> </html>
In this modified code, the button element is wrapped inside a div element. When the button is clicked, this still points to the button element itself, not its parent element div. Therefore, the jQuery object that wraps the parent element of the button cannot be directly obtained through $(this). In this case, you can use $(this).parent() to get the parent element that wraps the button and perform further operations.
In general, the point of this in the click event depends on the element that triggered the event. If you need to get the element of the click event, you can use $(this) to operate. If you need to get other related elements, you can get them through the parent element of $(this) or other jQuery methods. Proficient in the direction of this in click events can help developers better handle events and operate DOM elements.
The above is the detailed content of Parse the pointer of this in the click event in jQuery. For more information, please follow other related articles on the PHP Chinese website!