附加的Javascript单元格会丢失样式和大小格式

时间:2011-03-09 01:50:48

标签: javascript append html-table

我有一个html表,在<body onLoad="appendTable('alphabetTable')">时会被javascript函数追加。问题是附加的单元格似乎与表的其余部分分离,丢失的单元格大小应该从{{1在<th>区域并删除边框。

在此处查看此行动:http://jsfiddle.net/48X5M/

HTML:

<thead>

JS:

<html>
<head>
<title>Alphabet Table</title>
<script language="javascript" type="text/javascript" src="js/table.js"></script>
<style type="text/css">
#alphabetTable {border:1px solid black;}
</style>
</head>
<body onLoad="appendTable('alphabetTable')">
<h1>Alphabet Table</h1>

<table id="alphabetTable">
<thead>
    <tr>
        <td>Header1</td>
        <td>Header2</td>
        <td>Header2</td>
        <td>Header2</td>
    </tr>
</thead>
<tbody>
</tbody>
</table>


</body>
</html>

单元格开始附加在function appendTable(id) { var tbody = document.getElementById(id).getElementsByTagName("tbody")[0]; var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; var i = 0; for (var r = 0; r < 4; r++) { var row = tbody.insertRow(r); for (var c = 0; c < 4; c++) { var cell = row.insertCell(c); cell.appendChild(document.createTextNode(alphabet[i++])); } } document.body.appendChild(tbody); } 标记处。我是否必须在javascript中指定样式?如果有这样的话,为了简单起见,有办法避免它吗?

1 个答案:

答案 0 :(得分:3)

您将tbody附加到页面的末尾,而不是将其附加到表格中。采取行document.body.appendChild(tbody);解决问题。 http://jsfiddle.net/Lajgn/

您的代码最终看起来像这样(为简单起见,删除了JS和CSS):

<body>
 <h1>Alphabet Table</h1>

 <table id="alphabetTable">
 <thead>
     <tr>
         <td>Header1</td>
         <td>Header2</td>
         <td>Header2</td>
         <td>Header2</td>
     </tr>
 </thead>

 </table>


 <tbody>
 <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr><tr><td>e</td><td>f</td><td>g</td><td>h</td></tr><tr><td>i</td><td>j</td><td>k</td><td>l</td></tr><tr><td>m</td><td>n</td><td>o</td><td>p</td></tr></tbody>
</body>

正如您所看到的,tbody最终表格外面,并使用默认格式结束。