HTML 中 id 属性的有效值是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/70579/
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
What are valid values for the id attribute in HTML?
提问by Mr Shark
When creating the id
attributes for HTML elements, what rules are there for the value?
在id
为 HTML 元素创建属性时,值有什么规则?
采纳答案by dgvid
For HTML 4, the answer is technically:
对于HTML 4,技术上的答案是:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号 (":") 和句点 (".")。
HTML 5is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.
HTML 5更加宽松,只说一个 id 必须至少包含一个字符,并且不能包含任何空格字符。
The id attribute is case sensitive in XHTML.
id 属性在XHTML 中区分大小写。
As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSSor a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.
作为一个纯粹的实际问题,您可能希望避免使用某些字符。句点、冒号和“#”在 CSS 选择器中具有特殊含义,因此您必须使用CSS 中的反斜杠或传递给 jQuery的选择器字符串中的双反斜杠来转义这些字符。想一想在您对 id 中的句点和冒号感到疯狂之前,您需要多久对样式表或代码中的字符进行转义。
For example, the HTML declaration <div id="first.name"></div>
is valid. You can select that element in CSS as #first\.name
and in jQuery like so: $('#first\\.name').
But if you forget the backslash, $('#first.name')
, you will have a perfectly valid selector looking for an element with id first
and also having class name
. This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name
(a hyphen rather than a period), instead.
例如,HTML 声明<div id="first.name"></div>
是有效的。您可以#first\.name
像这样在 CSS和 jQuery 中选择该元素:$('#first\\.name').
但是如果您忘记了反斜杠, $('#first.name')
,您将拥有一个完全有效的选择器,用于查找具有 idfirst
和 class的元素name
。这是一个很容易被忽视的错误。从长远来看,选择 id first-name
(连字符而不是句点)可能会更快乐。
You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName
or FirstName
?" because you will always know that you should type first_name
. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.
您可以通过严格遵守命名约定来简化您的开发任务。例如,如果您完全限制自己使用小写字符,并且总是用连字符或下划线分隔单词(但不能同时使用两者,选择一个,不要使用另一个),那么您就有了一个易于记忆的模式。你永远不会想知道“是它firstName
还是FirstName
?” 因为您将始终知道应该键入first_name
. 更喜欢骆驼壳?然后限制自己,没有连字符或下划线,并且始终始终使用大写或小写作为第一个字符,不要混合使用它们。
A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName"
in your HTML (lower-case 'f') and #FirstName { color: red }
in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.
现在一个非常模糊的问题是,至少有一个浏览器 Netscape 6错误地将 id 属性值视为区分大小写。这意味着,如果您输入id="firstName"
了 HTML(小写的“f”)和#FirstName { color: red }
CSS(大写的“F”),那么这个有问题的浏览器将无法将元素的颜色设置为红色。在本次编辑时,即 2015 年 4 月,我希望您没有被要求支持 Netscape 6。将其视为历史脚注。
回答by Peter Hilton
From the HTML 4 specification:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号 (":") 和句点 (".")。
A common mistake is to use an ID that starts with a digit.
一个常见的错误是使用以数字开头的 ID。
回答by Michael Thompson
You can technically use colons and periods in id/name attributes, but I would strongly suggest avoiding both.
从技术上讲,您可以在 id/name 属性中使用冒号和句点,但我强烈建议避免两者。
In CSS (and several JavaScript libraries like jQuery), both the period and the colon have special meaning and you will run into problems if you're not careful. Periods are class selectors and colons are pseudo-selectors (eg., ":hover" for an element when the mouse is over it).
在 CSS(以及一些 JavaScript 库,如 jQuery)中,句号和冒号都有特殊的含义,如果不小心就会遇到问题。句点是类选择器,冒号是伪选择器(例如,当鼠标悬停在一个元素上时,“:hover”)。
If you give an element the id "my.cool:thing", your CSS selector will look like this:
如果你给一个元素指定 id "my.cool:thing",你的 CSS 选择器将如下所示:
#my.cool:thing { ... /* some rules */ ... }
Which is really saying, "the element with an id of 'my', a class of 'cool' and the 'thing' pseudo-selector" in CSS-speak.
这真的是在说,用 CSS 来说,“id 为 'my' 的元素,一类 'cool' 和 'thing' 伪选择器”。
Stick to A-Z of any case, numbers, underscores and hyphens. And as said above, make sure your ids are unique.
坚持使用任何大小写、数字、下划线和连字符的 AZ。如上所述,请确保您的 ID 是唯一的。
That should be your first concern.
这应该是你首先关心的问题。
回答by álvaro González
jQuery doeshandle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write
jQuery确实处理任何有效的 ID 名称。您只需要转义元字符(即点、分号、方括号...)。这就像说 JavaScript 有引号的问题只是因为你不会写
var name = 'O'Hara';
回答by Mr Shark
Strictly it should match
严格来说应该匹配
[A-Za-z][-A-Za-z0-9_:.]*
But jquery seems to have problems with colons so it might be better to avoid them.
但是 jquery 似乎有冒号的问题,所以最好避免它们。
回答by Zaheer Ahmed
HTML5:
HTML5:
gets rid of the additional restrictions on the id attribute see here. The only requirements left (apart from being unique in the document) are:
摆脱对 id 属性的额外限制,请参见此处。剩下的唯一要求(除了在文档中是唯一的)是:
- the value must contain at least one character (can't be empty)
- it can't contain any space characters.
- 该值必须至少包含一个字符(不能为空)
- 它不能包含任何空格字符。
PRE-HTML5:
HTML5 之前:
ID should match:
ID 应匹配:
[A-Za-z][-A-Za-z0-9_:.]*
- Must Start with A-Z or a-z characters
- May contain
-
(hyphen),_
(underscore),:
(colon) and.
(period)
- 必须以 AZ 或 az 字符开头
- 可能包含
-
(连字符)、_
(下划线)、:
(冒号)和.
(句点)
but one should avoid :
and .
beacause:
但应该避免:
,.
因为:
For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". Best to avoid the confusion and stay away from using . and : altogether.
例如,一个 ID 可以被标记为“ab:c”并在样式表中被引用为 #ab:c 但作为元素的 id,它可能意味着 id“a”,类“b”,伪 -选择器“c”。最好避免混淆并远离使用 . 和:一共。
回答by Michael Benjamin
HTML5: Permitted Values for ID & Class Attributes
HTML5:ID 和类属性的允许值
As of HTML5, the only restrictions on the value of an ID are:
从 HTML5 开始,对 ID 值的唯一限制是:
- must be unique in the document
- must not contain any space characters
- must contain at least one character
- 在文档中必须是唯一的
- 不得包含任何空格字符
- 必须至少包含一个字符
Similar rules apply to classes (except for the uniqueness, of course).
类似的规则适用于类(当然,唯一性除外)。
So the value can be all digits, just one digit, just punctuation characters, include special characters, whatever. Just no whitespace. This is very different from HTML4.
所以该值可以是所有数字,只有一位数字,只是标点符号,包括特殊字符等等。只是没有空格。这与 HTML4 非常不同。
In HTML 4, ID values must begin with a letter, which can then be followed only by letters, digits, hyphens, underscores, colons and periods.
在 HTML 4 中,ID 值必须以字母开头,后面只能跟字母、数字、连字符、下划线、冒号和句点。
In HTML5 these are valid:
在 HTML5 中,这些是有效的:
<div id="999"> ... </div>
<div id="#%LV-||"> ... </div>
<div id="____V"> ... </div>
<div id="??"> ... </div>
<div id="?"> ... </div>
<div id="{}"> ... </div>
<div id="?"> ... </div>
<div id="??¤☆~¥"> ... </div>
Just bear in mind that using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (e.g., CSS, JavaScript, regex).
请记住,在 ID 值中使用数字、标点符号或特殊字符可能会导致其他上下文(例如,CSS、JavaScript、regex)出现问题。
For example, the following ID is valid in HTML5:
例如,以下 ID 在 HTML5 中有效:
<div id="9lions"> ... </div>
However, it is invalid in CSS:
但是,它在 CSS 中无效:
From the CSS2.1 spec:
来自 CSS2.1 规范:
In CSS, identifiers(including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
在 CSS 中,标识符(包括选择器中的元素名称、类和 ID)只能包含字符 [a-zA-Z0-9] 和 ISO 10646 字符 U+00A0 及更高,加上连字符 (-) 和下划线 ( _); 它们不能以一个数字、两个连字符或一个连字符后跟一个数字开头。
In most cases you may be able to escape characters in contexts where they have restrictions or special meaning.
在大多数情况下,您可以在具有限制或特殊含义的上下文中对字符进行转义。
W3C References
W3C 参考
HTML5
HTML5
The
id
attribute specifies its element's unique identifier (ID).The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
Note: There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
The attribute, if specified, must have a value that is a set of space-separated tokens representing the various classes that the element belongs to.
The classes that an HTML element has assigned to it consists of all the classes returned when the value of the class attribute is split on spaces. (Duplicates are ignored.)
There are no additional restrictions on the tokens authors can use in the class attribute, but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.
该
id
属性指定其元素的唯一标识符 (ID)。该值在元素的主子树中的所有 ID 中必须是唯一的,并且必须至少包含一个字符。该值不得包含任何空格字符。
注意:对于 ID 可以采用的形式没有其他限制;特别是,ID 可以仅包含数字、以数字开头、以下划线开头、仅包含标点符号等。
属性(如果指定)必须具有一个值,该值是一组以空格分隔的标记,表示元素所属的各种类。
HTML 元素分配给它的类包含当 class 属性的值在空格上分割时返回的所有类。(重复项被忽略。)
对于作者可以在 class 属性中使用的标记没有额外限制,但鼓励作者使用描述内容性质的值,而不是描述内容所需呈现的值。
回答by pdc
In practice many sites use id
attributes starting with numbers, even though this is technically not valid HTML.
实际上,许多站点使用id
以数字开头的属性,即使这在技术上是无效的 HTML。
The HTML 5 draft specificationloosens up the rules for the id
and name
attributes: they are now just opaque strings which cannot contain spaces.
在HTML 5规范草案放宽了规则的id
和name
属性:他们现在不能包含空格只是不透明的字符串。
回答by blacksun1
Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and JQuery. The following should work but it must be unique throughout the page and also must start with a letter [A-Za-z].
连字符、下划线、句点、冒号、数字和字母都适用于 CSS 和 JQuery。以下应该有效,但它必须在整个页面中是唯一的,并且必须以字母 [A-Za-z] 开头。
Working with colons and periods needs a bit more work but you can do it as the following example shows.
使用冒号和句点需要做更多的工作,但您可以按照以下示例进行操作。
<html>
<head>
<title>Cake</title>
<style type="text/css">
#i\.Really\.Like\.Cake {
color: green;
}
#i\:Really\:Like\:Cake {
color: blue;
}
</style>
</head>
<body>
<div id="i.Really.Like.Cake">Cake</div>
<div id="testResultPeriod"></div>
<div id="i:Really:Like:Cake">Cake</div>
<div id="testResultColon"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var testPeriod = $("#i\.Really\.Like\.Cake");
$("#testResultPeriod").html("found " + testPeriod.length + " result.");
var testColon = $("#i\:Really\:Like\:Cake");
$("#testResultColon").html("found " + testColon.length + " result.");
});
</script>
</body>
</html>
回答by Sergio
HTML5
HTML5
Keeping in mind that ID must be unique, ie. there must not be multiple elements in a document that have the same id value.
请记住,ID 必须是唯一的,即。一个文档中不能有多个具有相同 id 值的元素。
The rules about ID content in HTML5 are (apart from being unique):
HTML5 中关于 ID 内容的规则是(除了唯一之外):
This attribute's value must not contain white spaces. [...]
Though this restriction has been lifted in HTML 5,
an ID should start with a letter for compatibility.
This is the W3spec about ID (fr?n MDN):
这是关于 ID (fr?n MDN)的W3规范:
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters
Previous versions of HTML placed greater restrictions on the content of ID values
(for example, they did not permit ID values to begin with a number).