I'm having trouble figuring out how to maintain my table stripes after adding new rows to a table. If I change the .insertAfter()
selector to #names tr:last
it works as I would expect, however using tr:first
or tr:nth-child(x)
results in the new row and all rows below it being striped. When looking at the updated DOM in Chrome's developer tools everything looks normal. I'm hoping someone can explain to me why this isn't working. I feel like I must be missing something fundamental. Here's the code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.striped {
background-color: #silver;
}
</style>
<script type="text/javascript" src="jquery-1.4.3.js"></script>
<script type="text/javascript">
function stripes () {
$("tr:even").each(function () {
$(this).addClass("striped");
});
}
$(function () {
stripes();
$("#addRow").click(function () {
$("<tr><td>Kenny</td><td>Bania</td></tr>").insertAfter("#names tr:first");
stripes();
});
});
</script>
</head>
<body>
<div>
<a href="#" id="addRow">Add Row</a>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody id="names">
<tr>
<td>Jerry</td>
<td>Seinfeld</td>
</tr>
<tr>
<td>Elaine</td>
<td>Benes</td>
</tr>
<tr>
<td>George</td>
<td>Costanza</td>
开发者_运维知识库 </tr>
<tr>
<td>Cosmo</td>
<td>Kramer</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Thanks!
You need to remove .striped class first.
function stripes () {
$("tr").each(function () {
$(this).removeClass("striped");
});
$("tr:even").each(function () {
$(this).addClass("striped");
});
}
精彩评论