Home > Article > Web Front-end > Use jQuery to dynamically modify table row attributes
Title: Using jQuery to dynamically modify table row attributes
In web development, we often encounter the need to dynamically modify table row attributes. This function can be easily and efficiently implemented using jQuery. The following uses a specific code example to introduce how to use jQuery to dynamically modify table row attributes.
First, we need a simple HTML table structure:
<table id="myTable"> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> <tr data-id="1"> <td>小明</td> <td>20</td> <td>男</td> </tr> <tr data-id="2"> <td>小红</td> <td>22</td> <td>女</td> </tr> </table>
Next, we use jQuery in JavaScript to dynamically modify table row attributes. We can add a click event to the table row, and then modify the properties of the row in the event handler, such as changing the color or adding a class name.
$(document).ready(function(){ $("#myTable tr").click(function(){ // 获取当前点击的表格行的data-id属性 var id = $(this).attr("data-id"); // 根据id选择需要修改属性的行 var targetRow = $("#myTable tr[data-id='" + id + "']"); // 修改行的背景颜色为黄色 targetRow.css("background-color", "yellow"); // 添加一个类名highlight targetRow.addClass("highlight"); }); });
In the above code, we add a click event to the table row. When the table row is clicked, we first obtain the data-id attribute of the clicked row, and then select the row whose attributes need to be modified based on this attribute, and Change its background color to yellow, and add a class name highlight to highlight this line.
Finally, in the style sheet, we can define the style of the highlight class to provide a more obvious display effect for the selected rows:
.highlight { font-weight: bold; color: red; }
Through the above code example, we can use jQuery The function of dynamically modifying table row attributes, and changing the row style by clicking on the table row. This method is simple and efficient, and is suitable for many scenarios in web development where table styles need to be dynamically changed. Hope this example helps you.
The above is the detailed content of Use jQuery to dynamically modify table row attributes. For more information, please follow other related articles on the PHP Chinese website!