如何让 Javascript 函数将两个文本输入保存到一个文本 (.txt) 文件中?
因此,我正在编写一个网页,用户在两个文本区域字段中输入值,一旦他们单击提交按钮,程序就应该启动两个文本输入的下载并将它们保存到文本文件中。到目前为止,我已经弄清楚如何仅将其中一个文本输入保存到文本文件中,并且我一直在尝试弄清楚如何让我的 Javascript 函数为两个文本输入完成此操作。这是我的 html 和 javascript 代码:
function saveIndex() {
var myBlob = new Blob([document.getElementById('textbox').value], {
type: "text/plain"
});
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "textfile.txt";
anchor.click();
window.URL.revokeObjectURL(url);
document.removeChild(anchor);
}
<body>
<label for="textbox">Textbox1</label>
<textarea id="textbox1"></textarea>
<label for="bio">Textbox2</label>
<textarea id="textbox2"></textarea>
<button type="button" id="bt" value="Exporter" onclick="saveIndex()" for="textbox"> EXPORT </button>
</body>
我知道我可能需要为我的第二个 textarea 标记创建一个新的 Blob,但我已经尝试过,并且还尝试了不同的方法将其实现到我的函数中,但没有成功。我无法为第二个 textarea 标记创建另一个函数,这一切都必须在当前的 saveIndex() 函数内完成。任何帮助将不胜感激!
So I'm writing a webpage where the user inputs values into two textarea fields, and once they click on the submit button, the program is supposed to initiate a download of both text inputs and save them into a text file. So far, I've figured out how to have only one of the text inputs be saved to the text file, and I've been trying to figure out how to get my Javascript function to have this done for both text inputs. Here is my html and javascript code:
function saveIndex() {
var myBlob = new Blob([document.getElementById('textbox').value], {
type: "text/plain"
});
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "textfile.txt";
anchor.click();
window.URL.revokeObjectURL(url);
document.removeChild(anchor);
}
<body>
<label for="textbox">Textbox1</label>
<textarea id="textbox1"></textarea>
<label for="bio">Textbox2</label>
<textarea id="textbox2"></textarea>
<button type="button" id="bt" value="Exporter" onclick="saveIndex()" for="textbox"> EXPORT </button>
</body>
I know I need to probably create a new Blob for my second textarea tag, but I've tried that and also tried different ways to implement it into my function without any success. I cannot make another function for the second textarea tag, this must all be done within the current saveIndex() function. Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您试图获取 ID 为“textbox”的元素的值,但没有这样的元素。您有“文本框1”和“文本框2”。此代码将检索两者并将它们与换行符连接到您的 blob 中。
我已经修复了您的 HTML 中的一些错误(标签未与其输入正确链接),还请使用 let & const 而不是古老的 var!
You were trying to get the value of an element with an ID of 'textbox' but there wasn't such an element. You have 'textbox1' and 'textbox2'. This code will retrieve both and concatenate them with a newline into your blob.
I've fixed up some errors in your HTML (the labels not linking correctly with their inputs), also please use let & const instead of ancient var!