为什么浏览器会修改包含& #x的HTML元素的ID? [英] Why does the browser modify the ID of an HTML element that contains &#x?
问题描述
说我有这个HTML页面:
Say I've got this HTML page:
<html>
<head>
<script type="text/javascript">
function echoValue(){
var e = document.getElementById("/path/$whatever");
if(e) {
alert(e.innerHTML);
}
else {
alert("not found\n");
}
}
</script>
</head>
<body>
<p id="/path/$whatever">The Value</p>
<button onclick="echoValue()">Tell me</button>
</body>
</html>
我假设浏览器将ID字符串/path/$任何内容
视为简单字符串.实际上,它将$
转换为其呈现的表示形式( $
).
I would assume that the browser treats the ID-string /path/$whatever
as simple string. Actually, it converts the $
to it's rendered representation ($
).
但是,javascript代码使用文字字符串$
来搜索元素.因此,调用 document.getElementById
失败,并且我从没接触过该段落的值.
The javascript code however uses the literal string $
to search for the element. So, the call document.getElementById
fails and I never get hands on the value of the paragraph.
是否有一种方法可以强制浏览器从字面上使用给定的ID字符串?
Is there a way to force the browser into using the given ID string literally?
修改:
当然,我知道我不必逃避 $
.但是网页被生成,并且生成器进行转义.所以,我必须应付我所拥有的.
Of course I know that I don't have to escape the $
. But the web page gets generated and the generator does the escaping. So, I have to cope with what I've got.
推荐答案
在< p id ="...">
中,$
序列被解释为 $
,因为它出现在属性中并被视为HTML实体.其他所有元素属性也是如此.
In the <p id="...">
, the $
sequence is interpreted as $
, because it appears in an attribute and is treated as an HTML entity. Same goes for all other element attributes.
在< script>
元素中,根本不解释HTML实体,因此它会按字面显示.
In the <script>
element, HTML entities are not interpreted at all, so it shows up literally.
这篇关于为什么浏览器会修改包含& #x的HTML元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!