I've searched through here countless times for help in my projects and now I've finally created an account. I was hoping to get some clarification on an answer I found to a similar question that had functionality similar to what I wanted. I essentially want the user to click a button and download a CSS file with data that was pushed to an empty array with JavaScript.
我在这里搜索了无数次在我的项目中寻求帮助,现在我终于创建了一个帐户。我希望得到一些澄清,我发现一个类似问题的答案,其功能与我想要的相似。我基本上希望用户单击一个按钮并下载一个CSS文件,其中包含使用JavaScript推送到空数组的数据。
Here is the code I found that works to an extent (I have the function triggered on click within my actual code but this piece is the specific area I'm having troubles with.)
这是我发现的代码在某种程度上起作用(我在实际代码中点击了触发的功能,但这件事是我遇到麻烦的特定区域。)
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();
}
}
download('responsive.css', 'Hello world!');
I've found that this works fine in Chrome, however when I had someone else test this in Firefox it was downloaded as responsive.css.txt . I did some research to see if it's possible to change "data:text/plain" to "data:text/css" in line 3 of my code but I was told by my tester that he was still having the same problem. In addition if anyone would have a solution for this to function in IE that would be great because right now when you click the button to download nothing happens.
我发现这在Chrome中运行良好,但是当我在Firefox中测试它时,它被下载为responsive.css.txt。我做了一些研究,看看是否可以在我的代码的第3行中将“data:text / plain”更改为“data:text / css”,但我的测试人员告诉他,他仍然遇到同样的问题。此外,如果有人有一个解决方案,这将在IE中运行,这将是伟大的,因为现在当你点击按钮下载没有任何反应。
Thanks in advance!
提前致谢!
1 个解决方案
#1
0
if you set the type to download, it should work:
如果您设置要下载的类型,它应该工作:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute(
'href',
'data:application/download;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();
}
}
download('responsive.css', 'Hello world!');
See: https://jsfiddle.net/s5on5dau/1/
Good luck ;)
祝好运 ;)
#1
0
if you set the type to download, it should work:
如果您设置要下载的类型,它应该工作:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute(
'href',
'data:application/download;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();
}
}
download('responsive.css', 'Hello world!');
See: https://jsfiddle.net/s5on5dau/1/
Good luck ;)
祝好运 ;)