将HTML转换成数据:使用JavaScript text / html的链接 [英] Convert HTML to data:text/html link using JavaScript
问题描述
下面是我的HTML:
<a>View it in your browser</a>
<div id="html">
<h1>Doggies</h1>
<p style="color:blue;">Kitties</p>
</div>
我如何使用JavaScript来使的href
我的链接点属性到Base64 EN codeD网页的源是的innerHTML
DIV#HTML
?
How do I use JavaScript to make the href
attribute of my link point to a base64 encoded webpage whose source is the innerHTML
of div#html
?
基本上,我想要做的,除了同样的转换完成这里(与以base64复选框选中)在JavaScript中。
I basically want to do the same conversion done here (with the base64 checkbox checked) except for in JavaScript.
推荐答案
一个数据-URI与MIME类型的text / html
的>有可能成为这些格式之一:
Characteristics of a data-URI
A data-URI with MIME-type text/html
has to be in one of these formats:
data:text/html,<HTML HERE>
data:text/html;charset=UTF-8,<HTML HERE>
基-64编码是没有必要的。如果你的code包含非ASCII字符,如 EE
,的charset = UTF-8
必须是补充说。
以下字符必须进行转义:
The following characters have to be escaped:
-
#
- Firefox和Opera间preT这个人物作为哈希的标记(如的location.hash
)。 -
%
- 这个字符用于转义字符。逃离这个角色,以确保不会出现副作用。
#
- Firefox and Opera interpret this character as the marker of a hash (as inlocation.hash
).%
- This character is used to escape characters. Escape this character to make sure that no side effects occur.
此外,如果要嵌入在一个锚标记code,以下字符也应该进行转义:
Additionally, if you want to embed the code in an anchor tag, the following characters should also be escaped:
-
和/或
- 行情标记属性的值 -
&放大器;
- 和符号是用来标记HTML实体 -
&LT;
和&GT;
做的没有转义的一个HTML属性中。但是,如果你要嵌入在HTML中的链接,这些也应该被转义(%3C和%3E
)
" and/or '
- Quotes mark the value of the attribute.&
- The ampersand is used to mark HTML entities.<
and>
do not have to be escaped inside a HTML attribute. However, if you're going to embed the link in the HTML, these should also be escaped (%3C and %3E
)
如果你不介意的数据URI的大小,这样做最简单的方法是使用<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/en$c$cURIComponent\"><$c$c>en$c$cURIComponent$c$c>:
If you don't mind the size of the data-URI, the easiest method to do so is using encodeURIComponent
:
var html = document.getElementById("html").innerHTML;
var dataURI = 'data:text/html,' + encodeURIComponent(html);
如果大小事,你最好去掉所有连续的空白(这可以安全地完成,除非HTML包含&LT; pre&GT;
元/ 风格)。于是,只能更换显著字符:
If size matters, you'd better strip out all consecutive white-space (this can safely be done, unless the HTML contains a <pre>
element/style). Then, only replace the significant characters:
var html = document.getElementById("html").innerHTML;
html = html.replace(/\s{2,}/g, '') // <-- Replace all consecutive spaces, 2+
.replace(/%/g, '%25') // <-- Escape %
.replace(/&/g, '%26') // <-- Escape &
.replace(/#/g, '%23') // <-- Escape #
.replace(/"/g, '%22') // <-- Escape "
.replace(/'/g, '%27'); // <-- Escape ' (to be 100% safe)
var dataURI = 'data:text/html;charset=UTF-8,' + html;
这篇关于将HTML转换成数据:使用JavaScript text / html的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!