简体   繁体   English

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

[英]Javascript reverse engineering: Convert html table to string/text

Currently I have a table variable which I want to get its table content in this way: <table><tr></tr></table> instead of getting a Javascript object. 目前我有一个表变量,我希望以这种方式获取其表内容: <table><tr></tr></table>而不是获取Javascript对象。 Is there a solution to finding a method that could do that? 有没有找到可以做到这一点的方法的解决方案?

尝试innerHTML

This assumes your table is the only table on the page. 这假设您的表是页面上唯一的表。 If this is not the case, give it a unique ID (such as tableID ) and reference using getElementsById("tableID") . 如果不是这种情况,请使用getElementsById("tableID")为其指定唯一ID(例如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

You can see this in action in a short demo . 您可以在简短的演示中看到这一点

The pertinent things to learn are: 相关的要学习的东西是:

  • getElementsByTagName - get DOM elements by their tag name getElementsByTagName - 按标记名称获取DOM元素
  • attributes - a DOM property that gets an attributes array attributes - 获取属性数组的DOM属性
  • innerHTML - gets a string of the HTML inside any DOM object innerHTML - 在任何DOM对象中获取HTML的字符串
  • nodeName - gets the name of any DOM object nodeName - 获取任何DOM对象的名称

If you get into using a framework, jquery's .html() method and the getAttributes plugin would potentially also be helpful 如果你开始使用框架, jquery的 .html()方法和getAttributes插件可能也会有所帮助

Try following code... 试试以下代码......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM