我正在寻找带有脚本的帮助,该脚本将允许用户通过单击“导出”按钮从文本区域下载输出(通过提示他们保存输出)。
<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="OUTPUT">
</textarea>
我得到的最接近的答案是下面的内容,但是显然它是在创建文件,而不使用我的输出:
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
任何帮助都会受到的极大支持,表示赞赏。
最佳答案
使用您的方法,只需将textarea的值传递到createObjectURL函数即可。
<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="This text will be downloaded as a file.">
</textarea>
<br>
<button id="download">Download</button>
<script>
document.getElementById('download').addEventListener("click", download);
function download(){
var text = document.getElementById('output');
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([text.value], {type: 'text/plain'}));
a.download = 'test.txt';
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
}
</script>