如何在 HTML 正文中编码引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1664208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to encode quotes in HTML body?
提问by Matt Rogish
Should I encode quotes (such as " and ' -> ”
and ’
) in my HTML body (e.g. convert <p>Matt's Stuff</p>
to <p>Matt’s Stuff</p>
)? I was under the impression I should, but a co-worker said that it was no big deal. I'm dubious but I can't find anything that says it is forbidden. Am I mistaken? Is it a best-practice to encode? Or is it simply useless?
我应该在我的 HTML 正文中编码引号(例如 " 和 ' ->”
和’
)(例如转换<p>Matt's Stuff</p>
为<p>Matt’s Stuff</p>
)?我的印象是我应该,但一位同事说这没什么大不了的。我很怀疑,但是我找不到任何说它被禁止的东西。我错了吗?编码是最佳实践吗?还是根本没用?
回答by Guffa
Encoding quotation marks (") is in practice only needed if the're inside an attribute, however for the HTML code to be correct (passing HTML validation), you should always encode quotation marks as "
.
编码引号 (") 实际上只在属性内部时才需要,但是为了使 HTML 代码正确(通过 HTML 验证),您应该始终将引号编码为"
.
Apostrophes (') don't need escaping in HTML. In XHTML they should be encoded as '
.
撇号 (') 在 HTML 中不需要转义。在 XHTML 中,它们应该被编码为'
.
回答by Asaph
If you want your markup to be parsable as XML, you'll want to encode the following:
如果您希望标记可解析为 XML,则需要对以下内容进行编码:
& => &
< => <
> => >
" => "
' => '
Definitely do this in attributes whether you're trying to make your code XML compliant or not.
无论您是否试图使您的代码符合 XML,都一定要在属性中执行此操作。
回答by Amber
Typicaly such isn't necessary unless you're placing such values into a tag's attribute (or other places where having quote marks would throw off parsing). In regular body text un-encoded will work fine.
通常这不是必需的,除非您将这些值放入标签的属性中(或其他带有引号会导致解析失败的地方)。在常规正文中,未编码的文本可以正常工作。
<img src="..." alt="A "quote mark" in an alt attribute" />
回答by Gumbo
No, you only need to use character references for quotes (single or double) if you want to use them inside an attribute value declaration that uses the same quotes for the value declaration:
不,如果您想在对值声明使用相同引号的属性值声明中使用它们,则只需要对引号(单引号或双引号)使用字符引用:
title="The sign says "Matt's Stuff""
title='The sign says "Matt's Stuff"'
Both title values are The sign says "Matt's Stuff"
.
两个标题值都是The sign says "Matt's Stuff"
。