我想下载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标签。

任何人都有一个想法如何做到这一点? :)

最佳答案

将textToWrite分配更改为此:

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

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

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


您可以看到它在这个小提琴中起作用:
http://jsfiddle.net/fwe2wkqq/2/

10-07 14:54