动态创建HTML表格[转载自MSDN]

我的随笔
使用mshtml为html文件写入数据[代码]

中参考的文章

Visual Studio .Net 2003合并集合中
地址:
ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/dhtml/workshop/author/tables/buildtables.htm

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

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.

  1. Create opening and closing table tags.
  2. Place tr tags within the table tags; the tr tags denote rows.
  3. Place td tags within the tr tags; the td tags denote cells within rows.

Show Example

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 apply to the whole table, and so on.
tHead Defines the header section of a table. Use tr elements to create multiple rows within a tHead element.
tBody Defines the body of a table. You can use tBody elements to format parts of a table. For example, you can have multiple tBody elements in a table, each with different colors or fonts. The following example demonstrates this technique.
tr Defines a table row. Rows typically host one or more cells, and you can use either the td or th element to define each cell.
td Defines a table data object. td elements are also referred to as cells.
th Defines a table header cell. The th element is similar to a td element, but it provides additional formatting appropriate for a column heading, such as centering the text and making it bold.
tFoot Defines a footer for a table. Like a tBody element, a tFoot must contain other elements. A tFoot can have multiple rows and columns by placing tr and td elements within the tFoot.
caption Provides a place for a brief description of the table. The caption is placed outside the borders of the table. By default, the caption appears at the top of the table, but you can place it at the bottom by using the VALIGN attribute.
col Specifies default values, such as width and background color, for the column.
colGroup Contains a group of columns. Use colGroup to specify the attributes, such as width and alignment, of a group of columns.

The following example shows how to use most of the elements listed in the preceding table. Notice how multiple tBody elements are used to add different background colors to the table.

Show Example

It is easy to use HTML to create tables that display static data. This data changes infrequently and is hard-coded into table format. However, consider cases in which the data changes frequently, and updates need to be made often—for example, stock quotes or scores from a sporting event. In these instances, you might want to use the Table Object Model to update these tables dynamically, as described in the following sections.

Creating and Manipulating Tables

This section explains how to use JScript and the Table Object Model to create and manipulate the content of tables.

The Table Object Model consists of:

Methods

The Table Object Model contains the following methods for creating and manipulating tables.

createTHead Creates an empty tHead element in the table.
deleteTHead Deletes the tHead element and its contents from the table.
createTFoot Creates an empty tFoot element in the table.
deleteTFoot Deletes the tFoot element and its contents from the table.
createCaption Creates an empty caption element in the table.
deleteCaption Deletes the caption element and its contents from the table.
insertRow Creates a new row in a table, tBody, tHead, or tFoot, and adds the row to the rows collection of that element.
deleteRow Deletes the specified row in the table and removes the row from the rows collection.
insertCell Creates a new cell in the table row and adds the cell to the cells collection.
deleteCell Deletes the specified cell in the table row and removes the cell from the cells collection.

Collections

Tables consist of multiple collections of elements. For example, a table contains a rows collection, and each row contains a cells collection. You can use indexes to access the members of a collection, making it easy to iterate through the collection.

The following collections are available through the Table Object Model.

tBodies Collection of all tBody objects in the table.
rows Collection of tr objects (rows) from a table object.
cells Collection of all cells in the table row or in the entire table.

tBodies

A table object provides access to three sections: tHead, tBody, and tFoot. The tBodies collection consists of all the bodies in a table. There can be only one tHead and one tFoot in a table. If more than one tHead is defined, the first one is considered the actual header for the table. The others are added to the tBodies collection.

The Table Object Model does not provide a method for creating tBody elements. However, you can use the DOM to create them. In fact, as you will learn later in this article, you must create a tBody when using the DOM to create a table.

rows

Every table contains a rows collection, which consists of all the rows in a table, including the header and footer rows. You can use the insertRow method to add a row to a table and, consequently, to its rows collection. Each row is equivalent to a tr element in HTML. The following code appends an empty row to the rows collection of a table called oTable.

var oRow
oRow = oTable.insertRow();

By default, the insertRow method appends a row to the end of the collection; this is faster than inserting a row somewhere in the middle of the collection. However, to insert a row into the middle of a collection, you can pass an index to insertRow, as shown in the following code.

var oRow
oRow = oTable.insertRow(3);

The index on the rows collection starts at zero. Therefore, the preceding code inserts a row at the fourth position of the rows collection of oTable. Once a row is created, you can insert cells into it. This is discussed in the next section.

Note   The innerText and innerHTML properties are read-only on the tr object. Therefore, you cannot use them to insert text or HTML into a row. You can, however, insert td objects into a row using the insertCell method. Then, you can insert text or HTML into the td objects by setting the innerText or innerHTML property of the cell.

You can access the members of the rows collection by using an index, the same way you access an array. Consider the following code, which iterates through the rows of oTable and sets the font to bold for each row. The code uses array syntax to access the individual members of the rows collection. The length property is used to determine the number of elements in a collection.

var curr_row;

for (curr_row = 0; curr_row < oTable.rows.length; curr_row++)
{
  oTable.rows[curr_row].style.fontWeight = "bold";
}

cells

After a row is created, you can add cells to it; each row contains a cells collection. To append cells to the cells collection of a row object, call the insertCell method of the row object.

Note   By default, the insertCell method adds cells to the end of the collection, because it is faster to add a cell at the end of a row than somewhere in the middle.

The following example inserts a row into a table, and then it inserts a cell into the newly inserted row.

var oRow;
var oCell;

oRow = oTable.insertRow();
oCell = oRow.insertCell();

Once an empty cell is added to a row, you can insert HTML into the cell by setting its innerHTML property.

var oRow;
var oCell;

oRow = oTable.insertRow();
oCell = oRow.insertCell();
oCell.innerHTML = "Download the latest version of <I>Internet Explorer</I> from here."

As with the rows collection, use array syntax to access members of the cells collection. You can use nested loops to iterate through every cell in every row. The following example sets the width of every cell in oTable to 20.

var oRow;
var curr_row, curr_cell;

for (curr_row = 0; curr_row < oTable.rows.length; curr_row++)
{
  oRow = oTable.rows[curr_row];

  for (curr_cell = 0; curr_cell < oRow.cells.length; curr_cell++)
  {
    oRow.cells[curr_cell].style.width = "20";
  }
}

The cells collection exposes either td or th elements, depending on whether you are accessing a normal row, a header row, or a footer row.

Indexes

Row and cell objects have index properties that indicate their position in the document tree. You can use an index property called sectionRowIndex to determine the position of an element relative to its section.

The following table lists the index properties available on row and cell objects.

sourceIndex Location of the element in the entire document tree.
rowIndex Index of the row in the context of the parent table.
sectionRowIndex Index of the row within its table section.
cellIndex Index of the cell within its parent row.

The following example uses the Table Object Model to create the example table used throughout this article.

Hide Example

<TABLE ID="oTable" BORDER BGCOLOR="lightslategray">
<TBODY ID="oTBody0"></TBODY>
<TBODY ID="oTBody1"></TBODY>
</TABLE>

<SCRIPT LANGUAGE="JScript">
// Declare variables and create the header, footer, and caption.
var oTHead = oTable.createTHead();
var oTFoot = oTable.createTFoot();
var oCaption = oTable.createCaption();
var oRow, oCell;
var i, j;

// Declare stock data that would normally be retrieved from a stock Web site.
var heading = new Array;

heading[0] = "Stock symbol";
heading[1] = "High";
heading[2] = "Low";
heading[3] = "Close";

var stock = new Array;

stock["0,0"] = "ABCD";
stock["0,1"] = "88.625";
stock["0,2"] = "85.50";
stock["0,3"] = "85.81";

stock["1,0"] = "EFGH";
stock["1,1"] = "102.75";
stock["1,2"] = "97.50";
stock["1,3"] = "100.063";

stock["2,0"] = "IJKL";
stock["2,1"] = "56.125";
stock["2,2"] = "54.50";
stock["2,3"] = "55.688";

stock["3,0"] = "MNOP";
stock["3,1"] = "71.75";
stock["3,2"] = "69.00";
stock["3,3"] = "69.00";

// Insert a row into the header.
oRow = oTHead.insertRow();
oTHead.bgColor = "lightskyblue";

// Insert cells into the header row.
for (i=0; i<4; i++)
{
  oCell = oRow.insertCell();
  oCell.align = "center";
  oCell.style.fontWeight = "bold";
  oCell.innerText = heading[i];
}

// Insert rows and cells into the first body.
for (i=0; i<2; i++)
{
  oRow = oTBody0.insertRow();
  for (j=0; j<4; j++)
  {
    oCell = oRow.insertCell();
	oCell.innerText = stock[i + "," + j];
  }
}

// Set the background color of the first body.
oTBody0.bgColor = "lemonchiffon";

// Insert rows and cells into the second body.
for (i=2; i<4; i++)
{
  oRow = oTBody1.insertRow();
  for (j=0; j<4; j++)
  {
    oCell = oRow.insertCell();
	oCell.innerText = stock[i + "," + j];
  }
}

// Set the background color of the second body.
oTBody1.bgColor = "goldenrod";

// Insert rows and cells into the footer row.
oRow = oTFoot.insertRow();
oCell = oRow.insertCell();
oCell.innerText = "Quotes are for example only.";
oCell.colSpan = "4";
oCell.bgColor = "lightskyblue";

// Set the innerText of the caption and position it at the bottom of the table.
oCaption.innerText = "Created using Table Object Model."
oCaption.style.fontSize = "10";
oCaption.align = "bottom";
</SCRIPT>

The tBody elements in the preceding example were defined using HTML, because you cannot use the Table Object Model to create tBody elements. As mentioned previously, if your table contains only one tBody, you do not need to create it because it is implied.

Table Object Model vs. the DOM

The Table Object Model is specific to tables, using methods such as insertRow and insertCell, whereas the DOM is more generic, because it may apply to all elements. The DOM incorporates the parent/child/sibling relationships by using the createElement method, appendChild method, previousSibling property, and nextSibling property. The DOM is powerful in that it allows you to use script to manipulate any element of a document. For more information about the DOM, see the About the W3C Document Object Model.

Creating a Table Using the DOM

You can use the Table Object Model to create and insert an element with a single call to the insertRow method. The DOM, however, requires two distinct steps: first a call to createElement to create an empty element, and then a call to appendChild to insert the element into the document tree. These two steps are required for all elements, including the table element.

One significant difference between using the Table Object Model and the DOM to create a table is that you must create a tBody element and insert it into the table when using the DOM. Since you are manipulating the document tree directly, the DOM does not create the tBody, which is automatically implied when using HTML.

DOM Structure

You can use the rows and cells collections and the Table Object Model to navigate through table elements. The DOM, however, is based on a tree structure and uses a parent/child/sibling relationship when accessing the nodes of the document. Because of this structural relationship, you must use properties such as firstChild and nextSibling to navigate a table through the DOM.

The following example shows how to use the DOM to navigate the document tree and change the background color of each cell in oTable.

Hide Example

var oParent = oTable.firstChild;
var oElement = oParent.firstChild;

// Navigate down the document tree until you find the first TD element.
while (oElement.tagName != "TD")
{
  oParent = oElement;
  oElement = oElement.firstChild;
}

while (oParent != null)
{
  while (oElement != null)
  {
    oElement.runtimeStyle.backgroundColor = "red";
    oElement.runtimeStyle.color = "white";
    oElement = oElement.nextSibling;
  }

  oParent = oParent.nextSibling;

  if (oParent != null)
  {
    oElement = oParent.firstChild;
  }

}

Finally, the following is an example that uses the DOM to create the same table that has been used throughout this document. Although more code is required with the DOM, it allows for more flexibility and control over the table.

Hide Example

<!-- Placeholder for the table -->
<DIV ID="oTableContainer"></DIV>

<SCRIPT LANGUAGE="JScript">
// Declare variables and create the header, footer, and caption.
var oTable = document.createElement("TABLE");
var oTHead = document.createElement("THEAD");
var oTBody0 = document.createElement("TBODY");
var oTBody1 = document.createElement("TBODY");
var oTFoot = document.createElement("TFOOT");
var oCaption = document.createElement("CAPTION");
var oRow, oCell;
var i, j;

// Declare stock data that would normally be imported from a stock Web site.
var heading = new Array;

heading[0] = "Stock symbol";
heading[1] = "High";
heading[2] = "Low";
heading[3] = "Close";

var stock = new Array;

stock["0,0"] = "ABCD";
stock["0,1"] = "88.625";
stock["0,2"] = "85.50";
stock["0,3"] = "85.81";

stock["1,0"] = "EFGH";
stock["1,1"] = "102.75";
stock["1,2"] = "97.50";
stock["1,3"] = "100.063";

stock["2,0"] = "IJKL";
stock["2,1"] = "56.125";
stock["2,2"] = "54.50";
stock["2,3"] = "55.688";

stock["3,0"] = "MNOP";
stock["3,1"] = "71.75";
stock["3,2"] = "69.00";
stock["3,3"] = "69.00";

// Insert the created elements into oTable.
oTable.appendChild(oTHead);
oTable.appendChild(oTBody0);
oTable.appendChild(oTBody1);
oTable.appendChild(oTFoot);
oTable.appendChild(oCaption);

// Set the table's border width and colors.
oTable.border=1;
oTable.bgColor="lightslategray";

// Insert a row into the header and set its background color.
oRow = document.createElement("TR");
oTHead.appendChild(oRow);
oTHead.bgColor = "lightskyblue";

// Create and insert cells into the header row.
for (i=0; i<4; i++)
{
  oCell = document.createElement("TH");
  oCell.innerText = heading[i];
  oRow.appendChild(oCell);
}

// Create and insert rows and cells into the first body.
for (i=0; i<2; i++)
{
  oRow = document.createElement("TR");
  oTBody0.appendChild(oRow);

  for (j=0; j<4; j++)
  {
    oCell = document.createElement("TD");
	oCell.innerText = stock[i + "," + j];
    oRow.appendChild(oCell);
  }
}

// Set the background color of the first body.
oTBody0.bgColor = "lemonchiffon";

// Create and insert rows and cells into the second body.
for (i=2; i<4; i++)
{
  oRow = document.createElement("TR");
  oTBody1.appendChild(oRow);

  for (j=0; j<4; j++)
  {
    oCell = document.createElement("TD");
	oCell.innerText = stock[i + "," + j];
    oRow.appendChild(oCell);
  }
}

// Set the background color of the second body.
oTBody1.bgColor = "goldenrod";

// Create and insert rows and cells into the footer row.
oRow = document.createElement("TR");
oTFoot.appendChild(oRow);
oCell = document.createElement("TD");
oRow.appendChild(oCell);
oCell.innerText = "Quotes are for example only.";
oCell.colSpan = "4";
oCell.bgColor = "lightskyblue";

// Set the innerText of the caption and position it at the bottom of the table.
oCaption.innerText = "Created using Document Object Model."
oCaption.style.fontSize = "10";
oCaption.align = "bottom";

// Insert the table into the document tree.
oTableContainer.appendChild(oTable);

</SCRIPT>

Sample Game Using the Table Object Model and the DOM

This section uses a sample game to demonstrate the Table Object Model and the DOM. The game includes an image divided into nine graphic files, all the same size, and scrambled in the cells of a table. The player clicks one cell and then another to swap the content of the cells. The point of the game is to unscramble the image.

The table is created using Table Object Model methods. The processing is done using DOM methods. The swapNode method is used to exchange the contents of two cells.



© 2003 Microsoft Corporation. All rights reserved.
posted @ 2005-04-18 23:01  蜡人张  阅读(2750)  评论(0编辑  收藏  举报