gpt4 book ai didi

javascript - 从 html pre 标签下载文本

转载 作者:行者123 更新时间:2023-11-30 15:30:49 26 4
gpt4 key购买 nike

我想下载我的 pre 标签包含的所有文本。

我试过这段代码:

 function saveTextAsFile() {
var textToWrite = document.getElementById('textArea').value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = "proxies.txt";

var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null) {
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
<pre id="textarea">
1
2
3
</pre>
<button type="button" value="save" id="save"> Save</button>

JSFiddle

但它似乎只适用于textarea,不适用于pre tag。

有人知道如何完成这个吗? :)

最佳答案

将 textToWrite 分配更改为此:

var textToWrite = document.getElementById('textarea').innerText;

然后删除“onclick”事件中对“destroyClickedElement”的引用,因为该函数在您的代码中不存在,而是使用匿名函数:

downloadLink.onclick = function(){
document.body.removeChild(downloadLink);
};

你可以看到它在这个 fiddle 中工作: http://jsfiddle.net/fwe2wkqq/2/

关于javascript - 从 html pre 标签下载文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42266658/

26 4 0