简体   繁体   English

如何用JavaScript替换标签html表中的样式以导出到CSV文件

[英]how to replace style in tag html table with JavaScript for export to CSV file

I try to replace all tags in the HTML table but when I try, it can't replace them because it has a style attribute in the <span> tag. 我尝试替换HTML表中的所有标签,但是当我尝试替换时,由于在<span>标签中具有style属性,因此无法替换它们。 Here is my HTML and JavaScript code. 这是我的HTML和JavaScript代码。

 function doCsv(){ var table = document.getElementById("myTable").innerHTML; var data = table.replace(/<thead>/g, '') .replace(/<\\/thead>/g, '') .replace(/<tbody>/g, '') .replace(/<\\/tbody>/g, '') .replace(/<tr>/g, '') .replace(/<\\/tr>/g, '\\r\\n') .replace(/<th>/g, '') .replace(/<\\/th>/g, ',') .replace(/<td>/g, '') .replace(/<\\/td>/g, ',') .replace(/<span>/g, '', '""') .replace(/<\\/span>/g, '', '""'); alert(data); } 
 <table width="100%" id="myTable" style="text-align: left;"> <tr> <th>test</th> <th>test</th> <th>test</th> <th>test</th> <th>test</th> </tr> <tr> <td>2016-11-21 09:45:32</td> <td>test test</td> <td>test</td> <td>2016-11-21 - 2016-11-21 (1)</td> <td><span style="color:green">test</span></td> </tr> </table> 

use .innerText instead of innerHTML to return just the text contents. 使用.innerText而不是innerHTML仅返回文本内容。

You can also use querySelectorAll("<any css code>") to narrow down your search. 您也可以使用querySelectorAll("<any css code>")缩小搜索范围。

In the example below, I have used two CSS tags: tr>th and tr>td which basically means 在下面的示例中,我使用了两个CSS标签: tr>thtr>td ,这基本上意味着

"any TH element that is a descendant of a TR element" “作为TR元素的后代的任何TH元素”

and

"any TD element that is a descendant of a TR element" “作为TR元素的后代的任何TD元素”

Combined with querySelectorAll() which returns an array of elements that I can then access using simple array methods like for loops querySelectorAll()结合使用,该方法返回一个元素数组,然后可以使用简单的数组方法(如for循环)访问该元素

UPDATE UPDATE

I updated the example so that it would generate a proper CSV file (more or less) by adding a nested querySelectorAll() function call to each TR element. 我更新了示例,以便通过向每个TR元素添加嵌套的querySelectorAll()函数调用来生成适当的CSV文件(或多或少)。

 function doCsv() { var _data = ""; var table = document.querySelectorAll("tr"); for (var i = 0; i < table.length; i++) { // each TR is stored in table[i] var entry = table[i]; // all TD and TH elements for that TR are stored in entry_children var entry_children = entry.querySelectorAll("td,th"); for (var u = 0; u < entry_children.length; u++) { _data += entry_children[u].innerText + ","; } // add return at end of last child TR/TH element _data += "\\r\\n"; } alert(_data); } doCsv(); 
 <table width="100%" id="myTable" style="text-align: left;"> <tr> <th>test</th> <th>test</th> <th>test</th> <th>test</th> <th>test</th> </tr> <tr> <td>2016-11-21 09:45:32</td> <td>test test</td> <td>test</td> <td>2016-11-21 - 2016-11-21 (1)</td> <td><span style="color:green">test</span> </td> </tr> </table> 

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

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