为什么浏览器会修改包含& #x的HTML元素的ID? [英] Why does the browser modify the ID of an HTML element that contains &#x?

查看:47
本文介绍了为什么浏览器会修改包含& #x的HTML元素的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个HTML页面:

Say I've got this HTML page:

<html>
  <head>
    <script type="text/javascript">
      function echoValue(){
        var e = document.getElementById("/path/&#x24;whatever");
        if(e) {
          alert(e.innerHTML);
        }
        else {
          alert("not found\n");
        }
      }
    </script>
  </head>
  <body>
    <p id="/path/&#x24;whatever">The Value</p>
    <button onclick="echoValue()">Tell me</button>
  </body>
</html>

我假设浏览器将ID字符串/path/&#x24;任何内容视为简单字符串.实际上,它将&#x24; 转换为其呈现的表示形式( $ ).

I would assume that the browser treats the ID-string /path/&#x24;whatever as simple string. Actually, it converts the &#x24; to it's rendered representation ($).

但是,javascript代码使用文字字符串&#x24; 来搜索元素.因此,调用 document.getElementById 失败,并且我从没接触过该段落的值.

The javascript code however uses the literal string &#x24; 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 ="..."> 中,&#x24; 序列被解释为 $ ,因为它出现在属性中并被视为HTML实体.其他所有元素属性也是如此.

In the <p id="...">, the &#x24; 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.

这篇关于为什么浏览器会修改包含&amp; #x的HTML元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆