用DOM中的内容点击按钮Javascript时触发文件下载 [英] Trigger a file download on click of button Javascript with contents from DOM

查看:109
本文介绍了用DOM中的内容点击按钮Javascript时触发文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载一个由DOM元素创建的文件。所以用户点击网页上的一个按钮,它会调用一个javascript方法,它可以获取DOM元素的内容并提示用户下载。

我可以在Javascript Var中获取DOM元素的内容。但不知道如何进一步进行。



用于抓取我正在使用的DOM元素:

  var elem = document.getElementById(userDownload); 


解决方案

我不确定我是否正确理解什么是您正尝试下载的内容。如果你有存储在变量中的内容(听起来像是一个元素的HTML?),你可以试试:

 ( #downloadbutton)。click(function(){
// var content =文件内容;
var dl = document.createElement('a');
dl.setAttribute(' href','data:text / csv; charset = utf-8,'+ encodeURIComponent(content));
dl.setAttribute('download','filename.txt');
dl.click ();
});


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.

I am able to grab contents of the DOM element inside a Javascript Var. But not sure how to proceed further.

For grabbing the DOM element i am using:

var elem = document.getElementById("userDownload");

解决方案

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:

("#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();
});

这篇关于用DOM中的内容点击按钮Javascript时触发文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆