[英]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: 相关的要学习的东西是:
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.