我想下载我的预标签包含的所有文字。
我试过这段代码:
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>
&#13;
但它似乎只适用于textarea,而不是预标签。
任何人都知道如何做到这一点? :)
答案 0 :(得分:2)
将textToWrite赋值更改为:
var textToWrite = document.getElementById('textarea').innerText;
然后在“onclick”事件中删除对“destroyClickedElement”的引用,因为代码中不存在该函数,而是使用匿名函数:
downloadLink.onclick = function(){
document.body.removeChild(downloadLink);
};
你可以看到它在这个小提琴中起作用: http://jsfiddle.net/fwe2wkqq/2/