encodeURIComponent() 忽略换行符

时间:2021-07-29 00:09:17

标签: javascript html

我正在尝试将 textarea 值保存到 .txt 文件中。

代码工作正常,但当我下载文件时,换行符没有保留,所有内容都打印在一行上。

代码:

var fname;
var fnote;

function download() {
  var element = document.createElement('a');
  fname = document.getElementById("title").value;
  fnote = document.getElementById("note").value;
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURI(fnote));
  element.setAttribute('download', fname);

  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}
<!DOCTYPE html>
<html>

<head>
  <title>Javascript - Create Text file</title>
</head>

<body>
  <form>
    <div>
      <p>title:</p>
      <input autocomplete="off" type="text" name="title" id="title" placeholder="Title.." style="border: solid 1px #957dad;">
    </div>
    <div class="form-group">
      <p>note:</p>
      <textarea name="note" rows="15" cols="70" id="note" placeholder="Enter your text here.." style="padding: 2%; border-color: #957dad; border-width: 3px; resize: none; max-width: 100%;"></textarea>
    </div>
    <input type="button" value="Download" onclick="download()" class="btn btn-primary">
  </form>
</body>

</html>

0 个答案:

没有答案