The following script helps to make html tables to have rows of alternating colors:
<script开发者_开发百科 type = "text/javascript">
$(document).ready(function () {
$("tr:even").css("background-color", "#e8eef4");
});
$(document).ready(function () {
$("tr:odd").css("background-color", "#fff");
});
</script>
It works ok, but the problem is that it applies this rule to all tables in its scope, and I'd like it to be applied to several tables only.
How I could apply such a script to specific tables only?
Change your selector (tr:even
or tr:odd
) to .CLASSNAME tr:even
and .CLASSNAME tr:odd
- then add CLASSNAME
to your containing tables where you want the stripes.
You should forget about using javascript and just use CSS
<style>
.myTable tr:nth-child(even) { background-color: #c5c5c5; }
.myTable tr:nth-child(odd) { background-color: #fff;}
</style>
<table class="myTable">
<tr>
<td>asdf</td>
</tr>
<tr>
<td>asdf</td>
</tr>
<tr>
<td>asdf</td>
</tr>
<tr>
<td>asdf</td>
</tr>
</table>
Here's a fiddle
http://jsfiddle.net/ZxvpX/1/
This will increase performance and reduce overhead simply because it doesn't require any additional libraries for such a menial task.
EDIT
as pointed out this doesn't work in IE. So you will need to load up the jQuery plugin to fix IE's broken system.
<RANT>
COME ON ALREADY MICROSOFT!!! WE ALL KNOW YOUR DEVELOPERS
READ THESE QUESTIONS ON STACKOVERFLOW AND FULLY UNDERSTAND
THE FRUSTRATION BEING EXPRESSED ON A DAILY BASIS.
GET WITH THE PROGRAM ALREADY!
</RANT>
You can narrow the selector and combine your code, like this:
$(document).ready(function () {
$(".selector tr:even").css("background-color", "#e8eef4");
$(".selector tr:odd").css("background-color", "#fff");
});
.selector
is an example, but whatever your can identify those tables on will work, or if this is part of an AJAX request, use $("tr:even", context)
instead.
Set table classes for the tables you want it applied to such as
<table class="even-odd"/>
<tr></tr>
<tr></tr>
</table>
Then Adjust your jQuery selectors to select all tables with the appropriate class and the descendant tr of that table only.
<script type = "text/javascript">
$(document).ready(function () {
$("table.even-odd tr:even").css("background-color", "#e8eef4");
});
$(document).ready(function () {
$("table.even-odd tr:even").css("background-color", "#fff");
});
</script>
I would personally just suggest using CSS properties
table.even-odd tr:nth-child(even) { background-color: #e8eef4; }
table.even-odd tr:nth-child(odd) { background-color: #fff;}
精彩评论