繁体   English   中英

如何在JavaScript函数的build html内编写脚本标签?

[英]How to write script tag inside build html in a javascript function?

我正在尝试打开html(内部js函数)以在新选项卡上显示表格。 现在,我试图为用户添加一个js函数,以供用户以excel格式下载表格,但是,一旦我尝试添加标记代码中断,我就会尝试添加该函数。

我尝试了以下操作:在js函数中的内置html代码的脚本标签内编写了下载功能。 添加了一个包含下载js函数的新javascript文件。 在变量中添加了下载功能,并尝试将其包含在脚本标签中。 使用<script>代替标签。

以下是我的代码:

var myfunction = function download() {
            $("#btnExport").click(function(e) {
                e.preventDefault();

                var data_type = "data:application/vnd.ms-excel";
                var table_div = document.getElementById("table_wrapper");
                var table_html = table_div.outerHTML.replace(/ /g, "%20");

                var a = document.createElement("a");
                a.href = data_type + ", " + table_html;
                a.download = "exported_table_" + Math.floor((Math.random() * 9999999) + 1000000) + ".xls";
                a.click();
            });
        };

        var html='<html><head><title>Locale Value</title><script>'+myfunction+'</script></head>'+
        '<body><h2>'+Header+'</h2><br><br><table>  <tr>    <th>Key</th>    <th>Value</th></tr>';

        for (var key in data) {
            var eachrow = '<tr>'
            + '<td>' + key + '</td>'
            + '<td>' + data[key] + '</td>'
            + '</tr>';
            html=html+eachrow;
        }
        html=html+'</table><br><br><button id="exportExcel" onclick="download()">Export</button></body></html>';
        return html;
    }

这里的问题是,一旦我关闭脚本标签(即),我的主脚本标签(其中写入了所有函数)就显示为关闭。 并出现在屏幕上。

在字符串中使用“ \\”。 符号“ \\ <”是“ <”的转义字符。

我已经更新了您的代码,请检查:

   $(function () {
    var myfunction = function download() {
        $("#btnExport").click(function (e) {
            e.preventDefault();

            var data_type = "data:application/vnd.ms-excel";
            var table_div = document.getElementById("table_wrapper");
            var table_html = table_div.outerHTML.replace(/ /g, "%20");

            var a = document.createElement("a");
            a.href = data_type + ", " + table_html;
            a.download = "exported_table_" + Math.floor((Math.random() * 9999999) + 1000000) + ".xls";
            a.click();
        });

    var html = '<html><head><title>Locale Value</title><script>' + myfunction + '</' + 'script></head>' +
    '<body><h2>' + Header + '</h2><br><br><table>  <tr>    <th>Key</th>    <th>Value</th></tr>';

    for (var key in data) {
        var eachrow = '<tr>'
        + '<td>' + key + '</td>'
        + '<td>' + data[key] + '</td>'
        + '</tr>';
        html = html + eachrow;
    }
    html = html + '</table><br><br><button id="exportExcel" onclick="download()">Export</button></body></html>';
    return html;
  };
});

暂无
暂无

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

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