[英]How do I prevent HTML encoding of '&' characters while copying content from a div to the title of the page?
I have a div whose contents are My Home & Administration 我有一个div,其内容是我的家和管理
<div id="abc"> My Home & Administration></div>
In the scripts, I need to copy the contents of this div to my page title. 在脚本中,我需要将此div的内容复制到我的页面标题。 Currently I am using innerHTML property which encodes the value.
目前我正在使用innerHTML属性来编码值。
<script type="text/javascript>
var id = document.getElementById("abc");
document.title = id.innerHTML;
</script>
The title is displayed as My Home & amp; 标题显示为My Home&amp; Administration (Note: disregard the space between & and amp;)
管理 (注意:忽略&和amp;之间的空间)
Is there any alternate way where the title is displayed as is? 是否有任何替代方式显示标题? I cannot use JQuery or any frameworks apart from pure and simple Javascript
我不能使用JQuery或任何框架,除了纯粹和简单的Javascript
Also note that this is not URL encoding but rather conversion of characters to their HTML entities. 另请注意,这不是URL编码,而是将字符转换为HTML实体。
You can use .textContent
instead of .innerHTML
. 您可以使用
.textContent
而不是.innerHTML
。
.innerHTML
is actually not part of the DOM spec. .innerHTML
实际上不是DOM规范的一部分。 Most browsers offer it as a non-standard feature. 大多数浏览器都将其作为非标准功能提供。 There are several problems with
.innerHTML
. .innerHTML
有几个问题。
Since you're interested in the actual text value of the node you can use .textContent
. 由于您对节点的实际文本值感兴趣,因此可以使用
.textContent
。
It might be useful to know that the div
abc actually has a node inside it, a TextNode
, which holds the value. 知道
div
abc实际上有一个节点,一个TextNode
来保存该值可能是有用的。 The div
itself doesn't actually hold the value. div
本身实际上并不具有价值。 If you were to traverse the DOM you would see this text node. 如果您要遍历DOM,您将看到此文本节点。
If your HTML is: 如果你的HTML是:
<div id="abc">Foo <strong>bar</strong> baz</div>
Your structure will be: 你的结构将是:
`div`:abc
TextNode Foo
`strong`
TextNode bar
TextNode baz
In this case abc.textContent
will return "Foo bar baz"
so it ignores the strong
tag. 在这种情况下,
abc.textContent
将返回"Foo bar baz"
因此它会忽略strong
标记。
In comparison .innerHTML
will return "Foo <strong>bar</strong> baz"
相比之下
.innerHTML
将返回"Foo <strong>bar</strong> baz"
Similarly for: 同样地:
<div id="abc">Foo&Bar</div>
.textContent
will be "Foo&Bar"
, .innerHTML
will be "Foo&Bar"
.textContent
将是"Foo&Bar"
,. .innerHTML
将是"Foo&Bar"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.