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

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

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

我意识到我有一个简单的解决方案,只需使用一个类。我只是好奇以这种方式使用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 :(

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

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

and

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

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

正如其他人在我之前说过的那样,简单的答案是否定的。一个元素不能有多个ID,一个ID在一个页面中不能使用多次。试一试,你就会发现它有多不管用。

针对tvanfosson关于在两个不同元素中使用相同ID的回答。据我所知,一个ID在一个页面中只能使用一次,不管它是否附加到不同的标记。

根据定义,需要ID的元素应该是唯一的,但如果需要两个ID,那么它就不是唯一的,而是需要一个类。

每个元素只能有一个ID,但确实可以有多个类。但不要有多个类属性;将多个类值放入一个属性中。

<div id="foo" class="bar baz bax">

完全合法。

不,如果你想沿着那条路径走,你应该使用嵌套的div。此外,即使您可以,想象一下当您运行document.getElementByID()时它会引起的混乱。如果有多个ID,它会抓取哪个ID ?

在稍微相关的主题中,您可以向DIV中添加多个类。

http://meyerweb.com/eric/articles/webrev/199802a.html