I've search through the similar questions but none answered my problem. (all those problems seemed related to typos)
I'm just making this for fun. I'm creating a table using jquery based on json data. Problem is, the appended table rows don't inherit any of the CSS rules. I feel like I've read about the cause for this before, specifically to tables, but the info eludes me.
HTML:
<table width="100%" class="" id="mytable">
<thead>
</thead>
<tbody>
<tr><td>f</td><td></td><td></td><td></td></tr>
<tr><td>b</td><td></td><td></td><td></td></tr>
<tr><td>a</td><td></td><td></td><td></td></tr>
</tbody>
</table>
CSS:
tr:nth-child(even){background:blue}
tr:nth-child(odd){background:green}
JS:
// Build some test data
var data = [];
var cols = ['Col-A','Col-B','Col-C','Col-D'];
for (i=0;i<10;i++){
data.push(['A_'+i,'B_'+i,'C_'+i,'D_'+i]);
}
// data that would be sent to
var json = JSON.stringify({columns:cols, data:data});
// build the table
$('#mytable').tables(json);
});
// the magic function
jQuery.fn.tables = function(json) {
var obj = JSON.parse(json);
var head = this.find('thead');
var bod = this.find('tbody');
// Build columns
head.append('<tr>');
for (i=0;i<obj.columns.length;i++){
head.append('<th>'+obj.columns[i]+'</th>');
}
head.append('</tr>');
// Add row data
for (i=0;i<obj.data.length;i++){
bod.append('<tr>');
for(j=0;j<obj.data[i].length;j++){
bod.append('<td>'+obj.data[i][j]+'</td>');
}
bod.append('</tr>');
}
return this;
}