日期:2009-07-04  浏览次数:21113 次

How to Build Tables Dynamically

--------------------------------------------------------------------------------


This article discusses the structure of HTML tables and explains how to use the Table Object Model to create them. It also compares how the Table Object Model and the Document Object Model (DOM) are used to create tables.

The Table Object Model, introduced in Microsoft® Internet Explorer 4.0, enables you to have dynamic control over the content of tables—for example, you can add rows and cells, change the contents of cells, and resize table elements. Dynamic control is useful in situations such as building a table based on the contents of a database, or building a table of calculated data, such as a calendar.

Note When using Dynamic HTML (DHTML) to create a document, you can create objects and set the innerText or innerHTML property of the object. However, because of the specific structure required by tables, the innerText and innerHTML properties of the table and tr objects are read-only.

This article assumes you know how to write Microsoft® JScript® (compatible with ECMA 262 language specification).

Table Structure
Creating and Manipulating Tables
Table Object Model vs. the DOM
Sample Game Using the Table Object Model and the DOM
Table Structure
As a reminder, here is a discussion about the structure of tables. Tables consist of rows and columns, arranged in a manner similar to a spreadsheet. The following steps and sample code show how to use HTML to create a table.

Create opening and closing table tags.
Place tr tags within the table tags; the tr tags denote rows.
Place td tags within the tr tags; the td tags denote cells within rows.
Show Example
<TABLE BORDER="1">
  <TR>
    <TD>Stock Symbol</TD>
    <TD>High</TD>
    <TD>Low</TD>
    <TD>Close</TD>
  </TR>
  <TR>
    <TD>ABCD</TD>
    <TD>88.625</TD>
    <TD>85.50</TD>
    <TD>85.81</TD>
  </TR>
  <TR>
    <TD>EFGH</TD>
    <TD>102.75</TD>
    <TD>97.50</TD>
    <TD>100.063</TD>
  </TR>
  <TR>
    <TD>IJKL</TD>
    <TD>56.125</TD>
    <TD>54.50</TD>
    <TD>55.688</TD>
  </TR>
  <TR>
    <TD>MNOP</TD>
    <TD>71.75</TD>
    <TD>69.00</TD>
    <TD>69.00</TD>
  </TR>
</TABLE>
Tables can also consist of headers, footers, captions, and multiple tBody elements. Most browsers automatically add the tBody tag to the HTML stream to create well-formed HTML.

You can use the following HTML elements to create tables.

table Wraps the entire table. Use the table element to apply formatting to the entire table. For example, use the table element to set the width of columns, set the border width, set colors that