How to use jquery to control the color of odd and even rows and active rows in a table
- 2020-03-30 02:40:08
- OfStack
Although jquery has been popular for many years, it has always been difficult, and I haven't taken the time to learn it. I just occasionally read it on a whim and then forget it after many days. Recently, I have to go to jquery to see the different colors of odd and even rows in the table. Although I still feel difficult, I am not as lost as before. After finishing have to sigh jquery is really great, do not have to write a lot of javascript functions to implement their own, a few simple easy to do.
First, define the odd-even row style of the table, as follows:
Then there is the page code:
If you don't need a mouse event, you can use CSS to control the color of the odd and even lines.
First, define the odd-even row style of the table, as follows:
body {
font-size:12px;
}
th {
color: #FFFFFF;
background: #A172AC;
}
table,table td,table th {
padding: 0.5em;
margin: 0;
border:0;
border-spacing:0;
}
table tbody tr.odd,
.odd {
background: #FBD106;
}
table tbody tr.even,
.even {
background: #E6453B;
}
.odd:hover,
.even:hover,
.hover {
background: #4BB747;
color: #FFFFFF;
}
Then there is the page code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> with jquery implementation table Odd and even rows in different colors </title>
<link href="style/mysql.css" rel="stylesheet" />
<script src="javascript/jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//Exclude th tags, th may have its own unique style, so define th style.
//$("tr:not(:has(th)):odd").addClass("odd");
//$("tr:not(:has(th)):even").addClass("even");
$("tr:odd").addClass("odd");
$("tr:even").addClass("even");
//If you don't have ".odd:hover" and ".even:hover" in your CSS, you need toggleClass().
});
</script>
</head>
<body>
<div id="outline">
<table>
<tr id="tth">
<th>data</th>
<th>data</th>
<th>data</th>
<th>data</th>
</tr>
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
</table>
</div>
</body>
</html>
If you don't need a mouse event, you can use CSS to control the color of the odd and even lines.
table tr:nth-child(even) td,
table tr:nth-child(even) th {
background-color: #FBD106;
}
table tr:nth-child(odd) td,
table tr:nth-child(odd) th {
background-color: #E6453B;
}