我知道在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。
当前回答
每个元素只能有一个ID,但确实可以有多个类。但不要有多个类属性;将多个类值放入一个属性中。
<div id="foo" class="bar baz bax">
完全合法。
其他回答
不。来自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.
这是专门的课程,而且 下面是你可以理解它的代码:
<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>
从7.5.2元素标识符:id和class属性:
id属性为元素赋值唯一标识符 由SGML解析器验证)。
and
ID和NAME标记必须以字母([a- za -z])开头,并且可以是 后面跟着任意数量的字母,数字([0-9]),连字符(“-”), 下划线(“_”),冒号(“:”)和时间(“。”)。
所以“id”必须是唯一的,不能包含空格。
每个元素只能有一个ID,但确实可以有多个类。但不要有多个类属性;将多个类值放入一个属性中。
<div id="foo" class="bar baz bax">
完全合法。
任何分配给div元素的ID都是唯一的。 但是,你可以在一个div元素下分配多个id,而不是“分配给”一个div元素。 在这种情况下,您必须将这些id表示为<span></span> IDs。
例如,您希望同一HTML页面中的两个链接指向页面中的相同div元素。
这两个不同的链接
<p><a href="#exponentialEquationsCalculator">Exponential Equations</a></p>
<p><a href="#logarithmicExpressionsCalculator"><Logarithmic Expressions</a></p>
指向页面的同一部分
<!-- Exponential / Logarithmic Equations Calculator -->
<div class="w3-container w3-card white w3-margin-bottom">
<span id="exponentialEquationsCalculator"></span>
<span id="logarithmicEquationsCalculator"></span>
</div>