在我的网站上,我有一个javascript,我希望在其中打开文件保存对话框。目的是将来自Web服务器的某些数据保存在文本文件中。
我正在尝试使用本文中显示的代码段:
[Using HTML5/JavaScript to generate and save a file
准确地说:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
此功能非常适合Firefox和Chrome。但是,对于Internet Explorer 11,它不起作用。当执行该指令时...
pom.dispatchEvent(event);
...什么都没有发生。保存对话框未打开,浏览器的Java控制台中未显示任何错误。事件似乎迷失了。任何帮助将不胜感激。
这在现代浏览器中得到广泛支持。但是,
较旧版本的IE支持等效的专有EventTarget.fireEvent()方法。
来源:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent