Javascript逆向工程:将html表转换为字符串/文本



目前我有一个表变量,我想以这种方式获得它的表内容:<table><tr></tr></table>而不是获得一个Javascript对象。有没有办法找到一种可以做到这一点的方法?

try innerHTML.

假设您的表是页面上唯一的表。如果不是这种情况,给它一个唯一的ID(如tableID)和引用使用getElementsById("tableID")

var tables = document.getElementsByTagName("table");
var firstTable = tables[0];
var tableAttr = firstTable.attributes;
// get the tag name 'table', and set it lower case since JS will make it all caps
var tableString = "<" + firstTable.nodeName.toLowerCase() + ">";
// get the tag attributes
for(var i = 0; i < tableAttr.length; i++) {
    tableString += " " + tableAttr[i].name + "='" + tableAttr[i].value + "'";
}
// use innerHTML to get the contents of the table, then close the tag
tableString += firstTable.innerHTML + "</" +
    firstTable.nodeName.toLowerCase() + ">";
// table string will have the appropriate content

您可以在一个简短的演示中看到这一点。

要学习的相关内容是:

  • getElementsByTagName -根据标签名获取DOM元素
  • attributes—获取属性数组的DOM属性
  • innerHTML -获取任何DOM对象内的HTML字符串
  • nodeName -获取任何DOM对象的名称

如果你开始使用框架,jquery的。html()方法和getAttributes插件可能也会有帮助

试试下面的代码…

<html>
<head>
    <script type="text/javascript">
        function sample_function(){
            alert(document.getElementById('div_first').innerHTML);
        }
    </script>
</head>
<body>
<div id="div_first">
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table></div>
    <button onclick="sample_function()">Click Here</button>
</body>
</html>

最新更新