我知道在HTML/XHTML页面中id必须是唯一的。
对于一个给定的元素,我可以给它分配多个id吗?
<div id="nested_element_123 task_123"></div>
我意识到我有一个简单的解决方案,只需使用一个类。我只是好奇以这种方式使用id。
我知道在HTML/XHTML页面中id必须是唯一的。
对于一个给定的元素,我可以给它分配多个id吗?
<div id="nested_element_123 task_123"></div>
我意识到我有一个简单的解决方案,只需使用一个类。我只是好奇以这种方式使用id。
当前回答
不,如果你想沿着那条路径走,你应该使用嵌套的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.
与别人说的相反,正确的答案是肯定的
Selectors规范对此非常清楚:
如果一个元素有多个ID属性,为了ID选择器的目的,所有这些属性都必须被视为该元素的ID。这种情况可以混合使用xml:id、DOM3 Core、xml dtd和特定于名称空间的知识来实现。
Edit
澄清一下:是的,一个XHTML元素可以有多个id,例如:
<p id="foo" xml:id="bar">
但是使用空格分隔的列表将多个id分配给同一个id属性是不可能的。
不,单个标记不能有多个id,但我见过带有name属性和id属性的标记,一些应用程序对它们的处理是相同的。
不。虽然W3C对HTML 4的定义似乎没有明确地涵盖您的问题,但name和id属性的定义表明标识符中没有空格:
ID和NAME令牌必须以字母([a- za -z])开头,后面可以是任意数量的字母、数字([0-9])、连字符("-")、下划线("_")、冒号(":")和句号(".")。
这是专门的课程,而且 下面是你可以理解它的代码:
<html>
<head>
<style type="text/css">
.personal{
height:100px;
width: 100px;
}
.fam{
border: 2px solid #ccc;
}
.x{
background-color:#ccc;
}
</style>
</head>
<body>
<div class="personal fam x"></div>
</body>
</html>