Home >Web Front-end >JS Tutorial >How to change table row attributes using jQuery
How to use jQuery to change the attributes of table rows
In web development, tables are a common way to display data. Sometimes we need to change the properties of table rows based on user operations or specific conditions, such as changing the row color, font, etc. This function can be easily achieved using jQuery.
The following is a simple example to illustrate how to use jQuery to change the attributes of table rows. First, we need a basic HTML structure:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>利用jQuery改变表格行的属性</title> <link rel="stylesheet" href="styles.css"> </head> <body> <table id="data-table"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> </thead> <tbody> <tr class="row"> <td>张三</td> <td>25</td> <td>男</td> </tr> <tr class="row"> <td>李四</td> <td>30</td> <td>女</td> </tr> <tr class="row"> <td>王五</td> <td>28</td> <td>男</td> </tr> </tbody> </table> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="script.js"></script> </body> </html>
Then create a new styles.css
file to define the style. The sample code is as follows:
.row { background-color: #f1f1f1; } .row.highlight { background-color: #ffcccb; }
Then create a new script.js
File for writing jQuery code:
$(document).ready(function() { $('.row').click(function() { $(this).toggleClass('highlight'); }); });
In the above code, we first select all table rows with row
class name through jQuery, and then Added a click event for these table rows. When the user clicks on a row, the highlight
class name of the row will be switched, thereby changing the background color of the row.
Through the above steps, we have implemented the function of using jQuery to change the attributes of table rows. In this way, users can change the style of the row by clicking on the row to achieve interactive effects. Of course, according to actual needs, we can also modify other attributes, such as text color, font size, etc.
In summary, using jQuery can easily realize the function of changing table row attributes. Through simple code, you can achieve some cool effects and add interactivity and beauty to the web page. I hope the above examples are helpful to developers who want to learn how to use jQuery to change table row properties.
The above is the detailed content of How to change table row attributes using jQuery. For more information, please follow other related articles on the PHP Chinese website!