2009-05-05 87 views
0

我使用HTML属性标题设置一些提示是这样的:即使在html源代码中,为什么html属性返回为'htmldecoded'?

<a href... title="Go to next chapter">Go</a> 

然后jQuery插件遍历所有[标题]属性,使美丽的提示。非常简单的一个新的div是为连接器创建的上述

<div style="position:absolute...">Go to next chapter</div> 

的问题是,标题是用户可编辑的,所以他可以写任何他想要的。我首先认为html编码很好,但事实证明我错了。 如果我有

<a id="a" title="&lt;script&gt;alert(10);&lt;/script&gt">Go</a> 

则提示股利如下:

<div style="position:absolute..."><script>alert(10)</script></div> 

1)为什么要查询其值当浏览器解码title属性?

2)我该如何解决它? (我知道,一个解决方案是双HTML编码,但它的awfull)

如何对它进行测试:考虑下面的代码

<html> 
<body> 
    <!-- encoding once, this doesn't work --> 
    <a id="a" title="&lt;script&gt;alert(10);&lt;/script&gt">atitle</a> 
    <!-- encoding twice, this works --> 
    <a id="b" title="&amp;lt;script&amp;gt;alert(10);&amp;lt;/script&amp;gt">btitle</a> 

    <script> 
    function w(x){ document.write(x.attributes["title"].value);} 
    w(a); // shows alert 
    w(b); // outputs it correctly into the page 
    </script> 
</body> 
</html> 

回答

1

1)的属性值是解码值 - 这是使的唯一途径感觉如果你想想。如果你设置一个javascript值为“\ n”,然后提醒它,你想返回“\ n”还是一个真正的换行符? title属性是文本...你只需要对它进行HTML编码就可以编写它。

2)你可以双击进行编码,或者你可以使用一个文本节点:

var node = document.createTextNode(x.attributes['title'].value); 
document.appendChild(node); 

这是首选的方法,那么蜘蛛/非JavaScript的浏览器将看到正确的标题属性。

相关问题