为什么浏览器会自动unescape html标签属性值?

pax*_*162 12 html browser tags attributes

下面我有一个HTML标记,并使用JavaScript来提取窗口小部件属性的值.此代码将提醒<test>而不是&lt;test&gt;,因此浏览器会自动unescapes属性值:

alert(document.getElementById("hau").attributes[1].value)
Run Code Online (Sandbox Code Playgroud)
<div id="hau" widget="&lt;test&gt;"></div>
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 除了对属性内容进行双重转义外,是否可以以任何方式阻止此行为?(这应该是这样的:&amp;lt;test&amp;gt;)
  2. 有谁知道浏览器为什么会这样?HTML规范中是否有任何地方明确提到此行为?

Sar*_*ran 6

1)可以进行双重逃避的情况下完成

看起来你的更接近htmlEncode().如果你不介意使用jQuery

alert(htmlEncode($('#hau').attr('widget')))

function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hau" widget="&lt;test&gt;"></div>
Run Code Online (Sandbox Code Playgroud)

如果您对纯香草js解决方案感兴趣

alert(htmlEncode(document.getElementById("hau").attributes[1].value))
function htmlEncode( html ) {
    return document.createElement( 'a' ).appendChild( 
        document.createTextNode( html ) ).parentNode.innerHTML;
};
Run Code Online (Sandbox Code Playgroud)
<div id="hau" widget="&lt;test&gt;"></div>
Run Code Online (Sandbox Code Playgroud)

2)为什么浏览器的行为如此?

只是因为这种行为,我们能够做一些特定的事情,比如在预先填充的输入字段中包含引号,如下所示,如果插入的唯一方法"是通过添加自己再次,这是不可能的需要逃避另一个像\

<input type='text' value="&quot;You &apos;should&apos; see the double quotes here&quot;" />
Run Code Online (Sandbox Code Playgroud)