日期:2014-05-16  浏览次数:20411 次

如何利用DOM解析表格里面的内容?
我知道可以用DOM创建表格,那么如何解析现有表格里面的内容呢?将里面的字符返回数组,让程序进一步处理。



例如这样的表格:

HTML code

<table>
<tr>
    <td>String1_1</td>
    <td>String1_2</td>
    <td>String1_3</td>
</tr>
<tr>
    <td>String2_1</td>
    <td>String2_2</td>
    <td>String2_3</td>
</tr>
<tr>
    <td>String3_1</td>
    <td>String3_2</td>
    <td>String3_3</td>
</tr>
<tr>
    <td>String4_1</td>
    <td colspan="2">String4_2</td>
  </tr>
</table>


------解决方案--------------------
object.rows 
object.rows(vIndex[,iSubIndex]) 

返回 数组 表格所有行 Array of tr objects.


object.cells 
object.cells(vIndex [,iSubIndex]) 

返回 数组 行的所有表格 Array of td and th elements contained by the object. If the object is a tr, the array contains elements only in that table row. If the object is a table, the array contains all elements in the table.



------解决方案--------------------
L@_@K
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> new document </title>
    <meta name="generator" content="editplus" />
    <meta name="author" content="Gao YiXiang" />
    <meta name="email" content="yixianggao@126.com" />
    <meta name="keywords" content="javascript dhtml dom" />
    <meta name="description" content="I love web development." />
</head>
<body>
    <table>
<tr>
    <td>String1_1</td>
    <td>String1_2</td>
    <td>String1_3</td>
</tr>
<tr>
    <td>String2_1</td>
    <td>String2_2</td>
    <td>String2_3</td>
</tr>
<tr>
    <td>String3_1</td>
    <td>String3_2</td>
    <td>String3_3</td>
</tr>
<tr>
    <td>String4_1</td>
    <td colspan="2">String4_2</td>
  </tr>
</table>
<script type="text/javascript">
<!--
var oTbe = document.getElementsByTagName("table")[0];
var aData = new Array(oTbe.rows.length);
for (var i=0; i<oTbe.rows.length; i++)
{
    aData[i] = new Array(oTbe.rows[i].cells.length);
    for (var j=0; j<oTbe.rows[i].cells.length; j++)
    {
        aData[i][j] = oTbe.rows[i].cells[j].innerHTML;
    }
}
alert(aData.join("\n"));
//-->
</script>
</body>
</html>