Home > Article > Web Front-end > How to get the current row of table in jquery
Method: 1. Use "$("tr").click(function(){})" to bind the click event to the table row element and set the processing function; 2. In the function, use " $(this).index() 1" just get the row number of the clicked element. The value obtained by index() starts counting from 0 and needs to be incremented by 1.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery gets the current row of the table
Gets the current row of the table (table), you can bind it to the table element Set a click event, which element is clicked, which is the current element; then determine the number of rows of the element.
Implementation idea:
Use click() to bind the click event to the table row element tr, and set the event processing function (tr defines the row in the HTML table)
In the processing function, use index() to obtain the position of the clicked element and obtain the number of rows of the clicked element.
Note: The element position obtained by index() is from If the count starts at 0, it needs to be added by 1.
Implementation code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-1.10.2.min.js"></script> <style> tr:nth-of-type(even) { background-color: red; } tr:nth-of-type(odd) { background-color: pink; } </style> <script> $(document).ready(function() { $("tr").click(function() { console.log("是表格的第 "+($(this).index()+1)+" 列"); }); }); </script> </head> <body> <table border="1"> <tr> <th>商品</th> <th>价格</th> </tr> <tr> <td>T恤</td> <td>¥100</td> </tr> <tr> <td>牛仔褂</td> <td>¥250</td> </tr> <tr> <td>牛仔库</td> <td>¥150</td> </tr> </table> <p>判断点击列是表格的第几列</p> </body> </html>
Description: The element position obtained by the
index() method is from 0 At the beginning, so if you want to get the accurate number of rows, you need to calculate it and add 1 to the obtained value.
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to get the current row of table in jquery. For more information, please follow other related articles on the PHP Chinese website!