如何将 div 中的源内容导出到 text/html 文件

2021-12-22 00:00:00 text export php javascript html

假设我有

... 一些 html ...</div> 我需要在这个 div 中获取 html 代码,将它放在一个文件中并强制以 TXT 格式下载它.

这怎么办?我应该使用 PHP 还是 JavaScript?我更喜欢 JavaScript.

解决方案

你可以这样使用:

更新了 jsfiddle,下载 btn(jquery)

使用普通 js 和自动执行的初始 jsfiddle

html

<span>你好</span>

html - 编辑(添加了执行此操作的链接)

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 扩展名

JS - 编辑

既然您在评论中说您使用的是 jQuery,我将从处理程序中调用此函数,而不是直接调用它.

$('#downloadLink').click(function(){downloadInnerHtml(fileName, 'main','text/html');});

您可以以文本形式下载,只需删除函数的第三个参数,它将采用默认值text/plain",并在文件名中添加扩展名 .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

相关文章