单击带有 DOM 内容的 Javascript 按钮触发文件下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25087009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trigger a file download on click of button Javascript with contents from DOM
提问by CodeMonkey
I want to download a file which is created from DOM element. So a user clicks a button on web page and it invokes a javascript method which may grab the contents of DOM element and prompt user for download.
我想下载一个从 DOM 元素创建的文件。因此,用户单击网页上的按钮并调用一个 javascript 方法,该方法可能会获取 DOM 元素的内容并提示用户下载。
I am able to grab contents of the DOM element inside a Javascript Var. But not sure how to proceed further.
我能够在 Javascript Var 中获取 DOM 元素的内容。但不确定如何进一步。
For grabbing the DOM element i am using:
为了抓取我正在使用的 DOM 元素:
var elem = document.getElementById("userDownload");
回答by user3758133
I am not sure if I understand correctly what is the content that you are trying to download. If you have the content (which sounds like the HTML of an element?) stored in a variable, you can try:
我不确定我是否正确理解您尝试下载的内容。如果您将内容(听起来像元素的 HTML?)存储在变量中,您可以尝试:
("#downloadbutton").click(function() {
//var content = content of file;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
dl.setAttribute('download', 'filename.txt');
dl.click();
});
回答by elzilrac
I appreciated finding this question, but at least on Firefox running with linux, you need to append the dl
element to the document to get the click functionality to work. I haven't tested extensively on other browsers how necessary this is, but it is necessary on some at least, so I recommend the following modification:
我很高兴找到这个问题,但至少在运行 linux 的 Firefox 上,您需要将dl
元素附加到文档中才能使单击功能正常工作。我没有在其他浏览器上广泛测试这是多么必要,但至少在某些浏览器上是必要的,所以我建议进行以下修改:
var content = document.getElementById("elem").innerHTML;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
dl.setAttribute('download', 'filename.txt');
// Set hidden so the element doesn't disrupt your page
dl.setAttribute('visibility', 'hidden');
dl.setAttribute('display', 'none');
// Append to page
document.body.appendChild(dl);
// Now you can trigger the click
dl.click();
回答by CodeMonkey
Figured it out: I had to do `
想通了:我必须做`
function myAlert(){
var content = document.getElementById("elem").innerHTML;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
dl.setAttribute('download', 'filename.txt');
dl.click();
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alertButton').addEventListener('click', myAlert);
});