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

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

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

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


当前回答

No.

话虽如此,没有什么能阻止你这么做。但是不同的浏览器会产生不一致的行为。不要这样做。每个元素一个ID。

如果需要对一个元素进行多个赋值,请使用classes(用空格分隔)。

其他回答

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

不,单个标记不能有多个id,但我见过带有name属性和id属性的标记,一些应用程序对它们的处理是相同的。

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

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

完全合法。

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

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

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

不。来自XHTML 1.0规范

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.