簡體   English   中英

Javascript逆向工程:將html表轉換為字符串/文本

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

目前我有一個表變量,我希望以這種方式獲取其表內容: <table><tr></tr></table>而不是獲取Javascript對象。 有沒有找到可以做到這一點的方法的解決方案?

嘗試innerHTML

這假設您的表是頁面上唯一的表。 如果不是這種情況,請使用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

您可以在簡短的演示中看到這一點

相關的要學習的東西是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM