問題描述
假設(shè)我有
TXT
格式下載它.這怎么辦?我應(yīng)該使用 PHP 還是 JavaScript?我更喜歡 JavaScript.
你可以這樣使用:
更新了 jsfiddle,下載 btn(jquery)
使用普通 js 和自動執(zhí)行的初始 jsfiddle
html
<span>你好</span>
html - 編輯(添加了執(zhí)行此操作的鏈接)
Js
function downloadInnerHtml(filename, elId, mimeType) {var elHtml = document.getElementById(elId).innerHTML;var link = document.createElement('a');mimeType = mimeType ||'文本/普通';link.setAttribute('下載', 文件名);link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));鏈接.點擊();}var fileName = 'tags.html';//如果需要,您可以使用 .txt 擴(kuò)展名
JS - 編輯
既然您在評論中說您使用的是 jQuery,我將從處理程序中調(diào)用此函數(shù),而不是直接調(diào)用它.
$('#downloadLink').click(function(){downloadInnerHtml(fileName, 'main','text/html');});
您可以以文本形式下載,只需刪除函數(shù)的第三個參數(shù),它將采用默認(rèn)值text/plain",并在文件名中添加擴(kuò)展名 .txt 而不是 html.
注意我編輯了這個答案,因為提問的人評論說他正在尋找如何讓它與處理程序一起工作,他讓它工作,但以防萬一.原代碼在jsfiddle
Let's say I have <div id="main"> ... Some html ...</div>
and I need to take the html code within this div, place it inside a file and force a download of it in TXT
format.
How can that be done? Should I use PHP or JavaScript? I would prefer JavaScript.
You could use something like this:
Updated jsfiddle with download btn(jquery)
Initial jsfiddle with plain js and autoexecution
html
<div id="main">
<span>Hey there</span>
</div>
html - Edit (Added a link to perform this action)
<a href="#" id="downloadLink">Download the inner html</a>
Js
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'tags.html'; // You can use the .txt extension if you want
JS - Edit
Since you said in the comments that you are using jQuery i'll call this function from a handler, instead of calling it directly.
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'main','text/html');
});
You can download as a text, just remove the third argument for function, and it will take the default which is "text/plain", and add the extension .txt to the filename instead of html.
Note I edited this answer since the person who asked commented that he was looking how to make it work with a handler, he made it work, but just in case. The original code is in the jsfiddle
這篇關(guān)于如何將 div 中的源內(nèi)容導(dǎo)出到 text/html 文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!