2015-11-02 60 views
6

当我尝试将多行代码写入输出文本文件时,不会保留换行符,并且所有内容都打印在一行上。输出文件中的新行字符

在具体的我有上点击关联此功能的监听按钮:

function (e) { 
    this.downloadButton.setAttribute("download", "output.txt"); 
    var textToSend = string1+"\r\n"+string2+"\r\n"+string3; 
    this.downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend); 
} 

正确下载该文件,但字符串1,字符串和STRING3是在同一条线上。

有什么建议吗?

+0

你使用的浏览器和操作系统? – baao

回答

4

我想你可能需要编码你的数据,你可以用encodeURIComponent()来做。

试试这个:

var textToSend = string1+"\r\n"+string2+"\r\n"+string3; 
textToSend = encodeURIComponent(textToSend); 
this.downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend) 
+0

谢谢,这解决了这个问题! – Andrea

3

使用encodeURIComponent()。见下面的工作示例。

var downloadButton = document.getElementById('download'); 
 
var textToSend = encodeURIComponent("string1\r\nstring2\r\nstring3"); 
 
downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend);
<a id="download" download="output.txt">Download</a>

+0

感谢您的回复。我之所以选择musefan的回复 – Andrea

相关问题