开发者

Appended Javascript cells lose style and size formatting

I have an html table that is getting appended by a javascript function when <body onLoad="appendTable('alphabetTable')"> The problem is that the appended cells seem to detach from the rest of the table, losing cell size they should inherit from the <th>'s in the <thead> region and dropping the border.

See it in action here: http://jsf开发者_如何转开发iddle.net/48X5M/

HTML:

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

JS:

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);
}

The cells start appending at the tbody tag. Do I have to assign styles within the javascript? If so is there a way to avoid it for simplicity sake?


You're appending the tbody to the end of the page instead of appending it to the table. Taking the line document.body.appendChild(tbody); out fixes the problem. http://jsfiddle.net/Lajgn/

Your code ends up looking like this (JS and CSS removed for simplicity):

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

As you can see, the tbody ends up outside the table and winds up using default formatting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜