Does the img tag's alt attribute require encoding?

我的梦境 提交于 2019-12-06 20:52:25

问题


In html does the text inside the img tag's alt attribute require encoding/escaping?

Non encoded example:

<img src="myimg.png" alt="image description" />

Encoded example:

<img src="myimg.png" alt="image%20description" />

回答1:


No, it does not need to be encoded like a URI. However, HTML characters must be encoded, like this...

<img src="myimg.png" alt="Me &amp; my image" />



回答2:


They do not require URL encoding, but they do require, as all XHTML attributes do, XHTML entity encoding.

Incorrect:

<img src="foo.gif" alt="Ben & Jerry's" />

Correct:

<img src="foo.gif" alt="Ben &amp; Jerry's" />

You would also need to encode double-quotes within the values, even though you don't have to do that in general text.

Reference:

  • http://www.w3.org/TR/xhtml1/#C_12



回答3:


No it does not. Encoding is for URLs as in http://en.wikipedia.org/wiki/Dream%20Theater, which the alt string is not.

You will need to use entity-encoding to escape > as &gt;, and " as &quot;, though. Note that that is different from URI encoding where special characters are encoded as a percent sign plus two hex digits.




回答4:


You should use HTML encoding (i.e. " becomes "), not URL encoding. If you are using ASP.NET you can achieve this with Server.HtmlEncode or better yet use the HtmlAttributeEncode method in the AntiXSS Library on CodePlex.



来源:https://stackoverflow.com/questions/1165635/does-the-img-tags-alt-attribute-require-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!