问题:尝试根据页面上的 div 内容构建有效的 html 文件下载,但我无法将内容包装在正确的标签中。
问题:如何添加 !DOCTYPE
, <head></head>
和<html></html>
标记到从提取的 div 内容构建的文件下载?
我无法在 div 中添加这些标签,因为 DOM 无法识别重复项。
当前代码:JS Fiddle
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
mimeType = mimeType || 'text/html';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'filename.html';
$('#download').click(function () {
downloadInnerHtml(fileName, 'downloadCode', 'text/html');
});
最佳答案
您是否尝试在从 div 中提取内容后添加包装数据?
var elHtml = document.getElementById(elId).innerHTML;
var fullHtml = "<!doctype html><html><head></head><body>" + elHtml + "</body></html>"
因为这是字符串处理而不是 DOM 操作,所以你基本上可以做任何你想做的事情。
关于javascript - 将 DOCTYPE 添加到从提取的 div 内容生成的下载文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25513077/