在Javascript中使用.js文件生成的格式表

时间:2014-03-04 19:31:43

标签: javascript html-table

我有一个用.js文件中的数据生成的表。我想要做的是能够格式化行ex。给他们不同的颜色。我知道你可以添加像<tr class="yellowrow"></tr>这样的类,但代码的方式我不能这样做。我在想一个for循环可能会......有什么想法吗?

<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.

2 个答案:

答案 0 :(得分: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"?

答案 1 :(得分:0)

如果您只是想要替换颜色,可以使用css选择器,如:

 tr:nth-child(odd)

http://www.w3.org/Style/Examples/007/evenodd.en.html