用jquery的.innerhtml下载文件在第一个“#”处中断

时间:2016-12-12 00:06:09

标签: javascript jquery

我有这段代码:

function download()
{
    var a = document.body.appendChild(document.createElement("a"));
    a.download = "CalExport.svg";

    var dd = document.getElementById('SvgResult');
    alert(dd.innerHTML); //displays fine

    a.href = "data:image/svg+xml," + dd.innerHTML;
    a.click();//downloaded file cuts off at the first "#"
}

当警报显示它没关系时,下载的版本会在第一个“#”之前被切断。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

由于这是href的一部分,因此您需要首先对数据进行url编码,例如

function download()
{
    var a = document.body.appendChild(document.createElement("a"));
    a.download = "CalExport.svg";

    var dd = document.getElementById('SvgResult');
    alert(dd.innerHTML); //should still display fine

    a.href = "data:image/svg+xml," + encodeURIComponent(dd.innerHTML);
    a.click();//should now not cut off.
}

网址中#的安全变体为%23%0A(请查看此工具:http://meyerweb.com/eric/tools/dencoder/)。

相关问题