除“&"符号外,还应在HTML href/src属性中编码其他哪些字符? [英] What other characters beside ampersand (&) should be encoded in HTML href/src attributes?

查看:122
本文介绍了除“&"符号外,还应在HTML href/src属性中编码其他哪些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

&"号是唯一应在HTML属性中编码的字符吗?

Is the ampersand the only character that should be encoded in an HTML attribute?

众所周知,这不会通过验证:

It's well known that this won't pass validation:

<a href="http://domain.com/search?q=whatever&lang=en"></a>

因为与号应为&amp;.这是

Because the ampersand should be &amp;. Here's a direct link to the validation fail.

此人列出了一堆应该编码的字符,但他错了.如果您在http://中对第一个"/"进行编码,则href将无法正常工作.

This guy lists a bunch of characters that should be encoded, but he's wrong. If you encode the first "/" in http:// the href won't work.

在ASP.NET中,是否已经建立了一个帮助程序来处理此问题?像Server.UrlEncode和HtmlEncode这样的东西显然不起作用-它们用于不同的目的.

In ASP.NET, is there a helper method already built to handle this? Stuff like Server.UrlEncode and HtmlEncode obviously don't work - those are for different purposes.

我可以构建自己的简单扩展方法(例如.ToAttributeView()),该方法可以进行简单的字符串替换.

I can build my own simple extension method (like .ToAttributeView()) which does a simple string replace.

推荐答案

除值的标准URI编码之外,&是您唯一需要担心的与HTML实体相关的唯一字符,因为这是每个HTML实体开头的字符.例如以下URL:

Other than standard URI encoding of the values, & is the only character related to HTML entities that you have to worry about simply because this is the character that begins every HTML entity. Take for example the following URL:

http://query.com/?q=foo&lt=bar&gt=baz

即使没有尾随的分号,因为& lt;是<的实体和& gt;是>的实体,某些旧的浏览器会将此URL转换为:

Even though there aren't trailing semi-colons, since &lt; is the entity for < and &gt; is the entity for >, some old browsers would translate this URL to:

http://query.com/?q=foo<=bar>=baz

因此您需要指定&作为& amp;以防止HTML解析文档中的链接发生这种情况.

So you need to specify & as &amp; to prevent this from occurring for links within an HTML parsed document.

这篇关于除“&"符号外,还应在HTML href/src属性中编码其他哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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