Home > Article > Web Front-end > What is the use of jquery eq() method
In jquery, the eq() method is used to return the element with the specified index number of the selected element. The syntax is "$(selector).eq(index)"; the value of the parameter "index" is Integer, used to specify the index number of the element, which can be negative (the index will be calculated from the end of the selected element). Note that index numbers start with 0, so the index number of the first element is 0 (not 1).
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
jquery eq() method
The eq() method is used to return the element with the specified index number of the selected element.
Syntax:
$(selector).eq(index)
index: Required. Specifies the index of the element, which can be an integer or a negative number. If a negative number is used, the index will be calculated from the end of the selected element.
Note: The index number (index) starts from 0, so the index number of the first element is 0 (not 1).
Usage Example
Example 1:Select the second
element (index number is 1)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("p").eq(1).css("background-color", "yellow"); }); </script> </head> <body> <h1>欢迎来到我的主页</h1> <p>我的名字叫Donald (索引号为 0).</p> <p>Donald Duck (索引号为 1).</p> <p>我住在 Duckburg (索引号为 2).</p> <p>我最好的朋友是 Mickey (索引号为 3).</p> </body> </html>
Example 2: Use a negative number to return the second
element from the end of the selected element.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("p").eq(-2).css("background-color", "yellow"); }); </script> </head> <body> <h1>欢迎来到我的主页</h1> <p>我的名字叫Donald (索引号为 0).</p> <p>Donald Duck (索引号为 1).</p> <p>我住在 Duckburg (索引号为 2).</p> <p>我最好的朋友是 Mickey (索引号为 3).</p> </body> </html>
Example 3:
If the element cannot be found based on the specified index parameter, this method constructs an jQuery object, length property is 0.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("p").eq(5).css("background-color", "yellow"); }); </script> </head> <body> <h1>欢迎来到我的主页</h1> <p>我的名字叫Donald (索引号为 0).</p> <p>Donald Duck (索引号为 1).</p> <p>我住在 Duckburg (索引号为 2).</p> <p>我最好的朋友是 Mickey (索引号为 3).</p> </body> </html>
Here, the background without the p element will turn yellow because of the sixth p element indicated by .eq(5)
.
[Recommended learning: jQuery video tutorial, web front-end】
The above is the detailed content of What is the use of jquery eq() method. For more information, please follow other related articles on the PHP Chinese website!