我知道在HTML/XHTML页面中id必须是唯一的。

对于一个给定的元素,我可以给它分配多个id吗?

<div id="nested_element_123 task_123"></div>

我意识到我有一个简单的解决方案,只需使用一个类。我只是好奇以这种方式使用id。


当前回答

与别人说的相反,正确的答案是肯定的

Selectors规范对此非常清楚:

如果一个元素有多个ID属性,为了ID选择器的目的,所有这些属性都必须被视为该元素的ID。这种情况可以混合使用xml:id、DOM3 Core、xml dtd和特定于名称空间的知识来实现。


Edit

澄清一下:是的,一个XHTML元素可以有多个id,例如:

<p id="foo" xml:id="bar">

但是使用空格分隔的列表将多个id分配给同一个id属性是不可能的。

其他回答

从7.5.2元素标识符:id和class属性:

id属性为元素赋值唯一标识符 由SGML解析器验证)。

and

ID和NAME标记必须以字母([a- za -z])开头,并且可以是 后面跟着任意数量的字母,数字([0-9]),连字符(“-”), 下划线(“_”),冒号(“:”)和时间(“。”)。

所以“id”必须是唯一的,不能包含空格。

Nay.

从3.2.3.1的id属性:

不能包含空格。

id="a b" <——查找该VaLuE中的空格字符。

也就是说,可以对多个id进行样式化。但如果您遵循规范,答案是否定的。

这很有趣,但据我所知,答案肯定是否定的。我不明白为什么您需要一个嵌套ID,因为您通常会与具有相同嵌套ID的另一个元素交叉。如果你不做,那就没有意义,如果你做了,那也没什么意义。

I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say "sysadm" and "team coordinator" having the id="sysadm teamcoordinator" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(

与别人说的相反,正确的答案是肯定的

Selectors规范对此非常清楚:

如果一个元素有多个ID属性,为了ID选择器的目的,所有这些属性都必须被视为该元素的ID。这种情况可以混合使用xml:id、DOM3 Core、xml dtd和特定于名称空间的知识来实现。


Edit

澄清一下:是的,一个XHTML元素可以有多个id,例如:

<p id="foo" xml:id="bar">

但是使用空格分隔的列表将多个id分配给同一个id属性是不可能的。