Home > Article > Web Front-end > Use the simple jQuery method toggleClass to change colors between rows_jquery
Today, a simple method toggleClass() was used to implement interlaced color changing: the code is as follows:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>隔行换色</title> <script src="js/jquery-1.4.2.min.js"></script> <style type="text/css"> body,table,td, { font-family:Arial, Helvetica, sans-serif; font-size:12px; } .h { background:#f3f3f3; color:#000; } .c { background:#ebebeb; color:#000; } </style> </head> <body> <div id="aaa"> <form> <table id="table" width="50%" border="0" cellpadding="3" cellspacing="1"> <tr> <td width="30" align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> <tr> <td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> <tr> <td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> <tr> <td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> <tr> <td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> <tr> <td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> <tr> <td align="center"><input type="checkbox" name="checkbox" class="check1" value="checkbox" /></td> <td>蓝枫前端</td> <td>蓝枫前端</td> </tr> </table> </form> </div> <script>
The first more complicated method:
$(function() { $("#table tr").hover(function() { $(this).addClass("h"); },function() { $(this).removeClass("h"); }) $("input").click(function() { if($(this).attr("checked")) { $(this).closest("tr").addClass("c"); } else { $(this).closest("tr").removeClass("c"); } }) })
The second simpler method:
toggleClass() Toggles setting or removing one or more classes of selected elements.
This method checks the specified class in each element. Adds the class if it does not exist, or removes it if it is set. This is called a toggle effect.
However, by using the "switch" parameter, you can specify that only classes be removed or only added.
$(function(){ $("#table tr").hover(function(){ $(this).toggleClass("h"); }) $("input").click(function(){ var d = $(this); d.closest('tr').toggleClass("c",d.attr("checked")) ; }) }) </script> </body> </html>