Reputation: 107
I have a table, populated from a JSon file, via an Ajax call. Very simply, I would like to change the background colour of the odd/even table rows.
The table is within a Jquery tab; would this make any difference?
$(document).ready(function(){
// $("#table tr:odd").css('background-color', 'red'); <!-- None of these appear to work -->
$("tr:odd").css("background-color","#eee");
// ***--- SPANISH MENU ---***
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: 'jsonp',
success: function (data) {
drawTable(data, 2);
}
});
// ***--- CREATE TABLE ---***
function drawTable(data, table_number) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i], table_number);
}
}
// ***--- CREATE ROW ---***
function drawRow(rowData, table_number) {
var row = $("<tr />")
$("#table" + table_number).append(row);
row.append($("<td>" + rowData.course + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.price + "</td>"));
}
HTML:
<div id="tabs">
<ul>
<li><a href="#tab-1">Italian</a></li>
<li><a href="#tab-2">Spanish</a></li>
</ul>
<div id="tab-1">
<table id='table1' border="1" cellpadding="15">
<tbody></tbody>
</table>
</div>
</div>
I've tried .addclass as well, but that doesn't seem to work either. Where am I going wrong?
Upvotes: 0
Views: 97
Reputation: 21672
You are trying to apply the style to the elements before they exist.
$("tr:odd").css("background-color","#eee");
will look for all odd rows, but because it's the very first line of your code (and the rows are not added until later), it won't find anything. If you wanted to do it this way, you'd have to change the colors after drawTable()
is complete and all rows are present.
But that being said, using JS for this is highly unnecessary. Just include a simple rule in CSS to take care of this for you:
tr:nth-child(odd) {
background: #eee;
}
Upvotes: 1