我有一个javascript,可以在点击时将<div>
的内容保存为html,这在Chrome上运行得很好,但在firefox上却没有。
请帮我写一个跨浏览器解决方案。
这是我的代码:
$(window).load(function(){
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 = 'invo.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'Invoice','text/html');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
CONTENT GOES HERE
</div>
<a href="#" onclick="return false;" id="downloadLink">Download</a>
答案 0 :(得分:5)
显然,只需在文档中添加临时链接即可修复Firefox中的问题;可能Firefox不喜欢click
不在“页面中”的元素:
$(window).load(function(){
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));
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
var fileName = 'invo.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'Invoice','text/html');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
CONTENT GOES HERE
</div>
<a href="#" onclick="return false;" id="downloadLink">Download</a>
顺便说一下,在这种情况下,您可以重新使用原始的“按钮”链接来保存下载和href,这样可以避免不必要的DOM更改:
$(window).load(function(){
function downloadInnerHtml(filename, elId, mimeType, link) {
var elHtml = document.getElementById(elId).innerHTML;
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
}
var fileName = 'invo.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'Invoice','text/html', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
CONTENT GOES HERE
</div>
<a href="#" id="downloadLink">Download</a>