我在点击链接下载文本区域内容时遇到问题
。
实际上我希望它能够存储以下内容:
java -jar(文本区域内容).jar
我希望 download
的名称为 'info.bat'
。因此,我尝试使用文本文件来执行此操作,但问题是它存储整个文档而不是仅存储文本区域内容。当我在 JSFiddle 中尝试它时,它给出一条错误消息,要求我将其发布到服务器然后下载它。我不想将数据发送到服务器,有什么办法吗?
JsFddile
这是 HTML 代码 -
<textarea id="textbox" rows="1" cols="30"></textarea>
<a href="#" download="info.txt" class="button">Download</a>
JS-
var anchor = document.querySelector('a#button');
var textbox = document.querySelector('#textbox');
anchor.onclick = function () {
anchor.href = (textbox.value);
anchor.download = 'info.txt';
};
编辑:
<html>
<head>
<title>Top</title>
<link rel="stylesheet" type="text/css" href="style.css">
<style type="text/css">
body
{
background-color: #fff;
}
textarea
{
position: absolute;
top: 30%;
left: 48%;
}
a
{
position: absolute;
top:50%;
left: 50%;
text-align: center;
text-decoration: none;
}
a:link, a:visited
{
display: block;
font-weight: bold;
background-color: #98bf21;
color: #fff;
border:2px solid #98bf21;
width: 120px;
height: 20px;
border-radius: 25px;
text-align: center;
padding: 4px;
text-decoration: none;
}
a:hover, a:active
{
color: #000;
background-color: #fff;
border:2px solid #98bf21;
}
</style>
</head>
<body>
<textarea id="textbox" rows="1" cols="30"></textarea>
<a href="#" download="info.txt" class="button">Download</a>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>-->
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var anchor = document.querySelector('a.button');
var textbox = document.querySelector('#textbox');
anchor.onclick = function ()
{
var blob = new Blob([textbox.value], {type: "text/plain;charset=utf-8"});
saveAs(blob, "info.txt");
//window.navigator.msSaveOrOpenBlob(blob, 'msSaveBlobOrOpenBlob_testFile.txt');
};
</script>
</body>
</html>
最佳答案
<textarea id="textbox" rows="1" cols="30"></textarea>
<a href="#" download="info.txt" class="button" id="button">Download</a>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var anchor = document.querySelector('a#button');
anchor.onclick = function(e) {
var textbox_text = document.querySelector('#textbox').value;
var textbox_file = new Blob([textbox_text], {"type":"application/bat"});
anchor.href = URL.createObjectURL(textbox_file);
anchor.download = "newtext.txt";
};
</script>
通过添加 ID 属性作为按钮,我能够下载内容而不是整个 HTML 代码。
关于javascript - 将文本区域内容下载为批处理文件 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30635974/