如何将div内的源内容导出为text / html文件 [英] How to export source content within div to text/html file

查看:966
本文介绍了如何将div内的源内容导出为text / html文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有< div id =main> ...一些html ...< / div> ,我需要在这个div中使用html代码,将其放在一个文件中,并强制以TXT格式下载它。
怎么办?我应该用PHP还是Javascript?我相当javascript。

解决方案

你可以使用这样的东西:



更新jsfiddle与下载btn(jquery)



简单js和自动执行的初始jsfiddle



html

 < div id =main> 
< span>嘿那里< / span>
< / div>

html - 修改(添加了一个链接来执行此操作) p>

 < a href =#id =downloadLink>下载内部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'; //你可以使用.txt扩展名,如果你想要

JS - 编辑



由于您在评论中表示您正在使用jQuery,我将从处理程序中调用此函数,而不是直接调用它。

  $('#downloadLink')点击(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 whithin 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 rather 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

这篇关于如何将div内的源内容导出为text / html文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆