【问题标题】:Tag inside JS breaking JS and stopping exportJS 内的标记破坏 JS 并停止导出
【发布时间】:2023-01-26 00:16:38
【问题描述】:

我正在尝试将 html 页面导出到 word 文档。我遵循了几个教程,但它们都在同一点中断。 该代码用于在脚本中设置标头,但在启动 html 标记时中断。如何将 html 页面导出为 doc 或 docx?

<script type="text/javascript">
    function Export2Doc(element, filename = ''){
        var html = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
        var footer = "</body></html>";
        var html = html+document.getElementById(element).innerHTML+footer;

    
        //link url
        var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
    
        //file name
        filename = filename?filename+'.doc':'document.doc';
    
        // Creates the  download link element dynamically
        var downloadLink = document.createElement("a");

        document.body.appendChild(downloadLink);
    
        //Link to the file
        downloadLink.href = url;
        
        //Setting up file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
        //Remove the a tag after donwload starts.
        document.body.removeChild(downloadLink);
    }
</script>

该脚本是从教程站点直接截取的。每一个都非常相似,但它们都在完全相同的点断裂。它们在 <body> 标记位于设置 var html 的行的引号内的位置断开。 我怎样才能解决这个问题以便我可以导出?

https://www.codexworld.com/export-html-to-word-doc-docx-using-javascript/

https://www.tutorialswebsite.com/export-html-to-word-document-with-javascript/

https://www.tutsplanet.com/export-html-to-ms-word-document-using-javascript/

【问题讨论】:

  • 问题在于您尝试分配给 html 变量的 HTML 字符串。问题是字符串没有正确关闭,特别是 <body> 标签没有关闭,这导致脚本标签中断。您可以通过正确关闭 <body> 标记来解决此问题。此外,您应该确保您的 <script> 标签已正确关闭,并且您没有遗漏任何其他结束标签,因为这会导致您的代码功能出现问题。

标签: javascript html export word


【解决方案1】:

问题似乎出在声明 html 变量的方式上。问题是您在同一范围内两次声明名为 html 的变量,这在 JavaScript 中是不允许的。

您可以通过将第二个变量重命名为不同的名称来解决此问题,例如:

var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var footer = "</body></html>";
var doc = header + document.getElementById(element).outerHTML + footer;

另外,请记住,此方法仅在您尝试导出的页面托管在服务器上时才有效,否则浏览器的安全策略将阻止脚本运行。

【讨论】:

  • 感谢您的建议,我会使用它,但是代码在 var html 最初构造的地方被破坏了。这条线。 var html = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='w3.org/TR/REC-html40'><head><metacharset='utf -8'><title>Export HTML To Doc</title></head><body>";行尾的 body 标签打断了 <script> 标签,其余代码显示在网页上。
猜你喜欢
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多