In web design, tables are a common layout method. However, if there are too many rows in the table, it may be difficult for users to distinguish between different rows, which affects user experience and usability. To solve this problem, developers can add some visual effects to distinguish different rows. In this article, we will use jQuery to change the row color in a table to improve user experience.
The first step is to set up the table in HTML. We'll illustrate this process using a simple table with three columns:
<table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> </thead> <tbody> <tr> <td>张三</td> <td>25</td> <td>男</td> </tr> <tr> <td>李四</td> <td>30</td> <td>男</td> </tr> <tr> <td>王五</td> <td>22</td> <td>女</td> </tr> <tr> <td>赵六</td> <td>28</td> <td>女</td> </tr> </tbody> </table>
Next comes the CSS part. We will set the style of the table and the color of the rows:
table { border-collapse: collapse; width: 100%; } th, td { padding: 8px; text-align: left; } tr { border-bottom: 1px solid #ddd; } tr.even { background-color: #f2f2f2; }
Here, we set the basic style for the table, including in-cell padding and borders. We also set the row style that changes color every other row to gray.
Now we will use jQuery to add styles to each row of the table. We will use a variable to track the parity of the current row and then add the class name "even" for the even rows.
$(document).ready(function() { $('table tbody tr:even').addClass('even'); });
This function first detects whether the document has been loaded and is ready for operation. It then uses a jQuery selector to select the tr sub-tag of each tbody tag in the table, filters out the even rows, and adds the class name "even" to each even row. After doing this, the even rows of the table will change the background color to make them more readable.
Through this example, we can see how to use jQuery and CSS to change the style of the table. This not only increases the visual impact of the web design, but also improves the user experience and makes the website easier to use.
The above is the detailed content of jquery changes tr dark color. For more information, please follow other related articles on the PHP Chinese website!