2014-03-04 26 views
1

我有一個使用.js文件中的數據生成的表。我想要做的是能夠格式行前。給他們不同的顏色。我知道你可以添加一個類,但代碼的方式我不能這樣做。我想一個for循環可能會..任何想法?使用javascript中的.js文件生成的格式表

<table id="data"> 
<thead> 
<tr> 
<th>Date</th> 
<th>Amount</th> 
<th>Name</th> 
</tr> 
</thead> 
<tbody> 
<script type="text/javascript" src="js/people.js"></script>//file with information 
<script type="text/javascript" > 
     for(var i=0; i<Name.length;i++){ 
document.write('<tr><td>' + date[i] + '</td><td>' + amount[i] + '</td><td>'    
+Name[i]'</td></tr>');//this brings in the data to generate the rows 
} 
</script> 
</tbody> 
//so this gives me a table with a couple of rows... how can i format each row they 
need to have different classes because they cant all have the same format.like one 
can be blue, another red, another blue..ect. 

回答

1

簡短回答:您可以使用CSS來設置不同的行的樣式。

tr:nth-child(2n){ 
    background-color: #ccc; 
} 

tr:nth-child(3n){ 
    background-color: #444; 
} 

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

長,大多是不相關的答案:你不應該使用document.write。你可以像這樣更加優雅地添加到tbody中。

<table id="data"> 
... 
<tbody></tbody> 
</table> 

<script> 
    var rows = []; 
    for (var i=0; i<Name.length; i++){ 
    rows.push(
     '<tr>' + 
     '<td>' + date[i] + '</td>' + 
     '<td>' + amount[i] + '</td>' + 
     '<td>' + Name[i] + '</td>' + 
     '</tr>' 
    ); 
    } 
    document.querySelector('#data tbody').innerHTML = rows.join(''); 
</script> 

Why is document.write considered a "bad practice"?

相關問題