gpt4 book ai didi

Javascript:转换 HTML 实体然后下载 HTML

转载 作者:行者123 更新时间:2023-12-03 04:31:15 25 4
gpt4 key购买 nike

我正在尝试将一个可在浏览器中运行的函数组合在一起:

  1. 获取元素内的 HTML
  2. 用 HTML 实体替换常见特殊字符(即将 © 转换为 ©),但替换对 HTML 至关重要的字符 ( < >/“' # . 等)
  3. 将替换后的 HTML 下载为文件,或者更好的是将该代码复制到剪贴板

我已经能够让以下内容适用于第 1 点和第 3 点,但替换功能似乎不适用于嵌套 HTML 元素中的字符。我在 javascript 方面不是很先进,并且无法找到解决方案。如有任何帮助,我们将不胜感激。

<div id="email-html">
<p>test ©</p>
</div>

<a id="ClickMe" onclick="(function () {
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
var coHtml = elHtml.replace(/©/g, '&copy;');
mimeType = mimeType || 'text/plain';

link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(coHtml));
link.click();
}

var fileName = 'email.html';
downloadInnerHtml(fileName, 'email-html', 'text/html');
})();
" href="#">Click to Download</a>

最佳答案

通过重新组织代码来消除内联 JavaScript 并遵循现代 Web 标准。它有效:

// Place this in a <script> tag that comes just before the closing body tag (</body>)

// Get a reference to the hyperlink
var a = document.getElementById("clickMe");

// Set up a click event handler for the hyperlink
// Because the handler needs arguments passed to it, wrap it
// within another function that will call the actual handler and pass
// those arguments
a.addEventListener("click", function () {
var fileName = 'email.html';
downloadInnerHtml(fileName, 'email-html', 'text/html');
});

function downloadInnerHtml(filename, elId, mimeType) {
// Better to use textContent instead of innerHTML here
var elHtml = document.getElementById(elId).textContent;
var link = document.createElement('a');
var coHtml = elHtml.replace(/©/g, '&copy;');

// Test to see the replaced content
console.log(coHtml);

// Commented as it is not relevant to the issue
//mimeType = mimeType || 'text/plain';

//link.setAttribute('download', filename);
//link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(coHtml));
//link.click();
}
<div id="email-html">
<p>test ©</p>
</div>

<a id="clickMe" href="#">Click to Download</a>

关于Javascript:转换 HTML 实体然后下载 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43477997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com