问题描述
我正在尝试在 HTML 中创建一个 textarea
以便我可以记录笔记。我希望能够按下保存按钮,将 textarea
中的文本下载到我的计算机。
我该怎么做?
我的 HTML 按钮代码是:
<a href="#" id="download">Download</a>
(看起来很奇怪,因为按钮位于下拉菜单下。
到目前为止,这是我的 Javascript 代码,但不起作用 :(
document.getElementById('download').onclick = function() {
_fix('click > download');
var text_new = _nl2br(data_a);
data_a = '';
var data = 'data:application/txt;charset=utf-8,' + encodeURIComponent(text_new);
this.href = data;
this.target = '_blank';
this.download = 'note.txt';
$(".chb").prop('checked',false);
}
解决方法
<!DOCTYPE html>
<html>
<head>
<style>
a{
text-decoration:none;
}
.btn {
display: inline-block;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
border: 1px solid transparent;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: transparent;
border-left-color: transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn-info {
color: #fff;
background-color: #17a2b8;
border-color: #17a2b8;
}
</style>
</head>
<body>
<input type='text' id='storyname' oninput="typeevent()" name='storyname' placeholder='FileName*' required />
<a id="export" class="btn btn-info" download="" href="#">Download</a>
<div id='editor' oninput="typeevent()" class="editorAria" contenteditable>
<p>? <b>The dashboard is in beta.</b> Every option may not works. [Clear the line and start typing]</p>
</div>
<!--SCRIPT-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function createDownloadLink(anchorSelector,str,fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = [str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject,fileName);
});
} else {
var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
$(anchorSelector).attr("download",fileName);
$(anchorSelector).attr("href",url);
}
}
function typeevent() {
var typed = document.getElementById("storyname").value;
$(function () {
if(typed==''){
}else{
var str = document.getElementById("editor").innerHTML;
createDownloadLink("#export",typed+".txt");
}
});
}
</script>
</body>
</html>