从javascript代码创建多行文本文件

时间:2018-05-10 16:36:41

标签: javascript php html

我找到了这段代码,但单击“下载”按钮后无法创建多行文本文件。它似乎只是一串文本...我尝试了不同的连接方式,但没有一个工作...

我无法弄清楚我错过了哪一件!

干杯:)

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
document.getElementById("dwn-btn").addEventListener('click', function(){
  // Generate download of hello.txt file with some content
  var text = `A rather long string of English text, an error message
actually that just keeps going and going -- an error
message to make the Energizer bunny blush (right through
those Schwarzenegger shades)! Where was I? Oh yes,
you\'ve got an error and all the extraneous whitespace is
just gravy.  Have a nice day`;

  var filename = "hello.txt";

  download(filename, text);
}, false);
<input type="button" id="dwn-btn" value="Download" />

0 个答案:

没有答案