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

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

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

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


当前回答

我想说技术上是可以的,因为真正呈现的内容在技术上总是依赖于浏览器。大多数浏览器都尽可能地遵循规范,据我所知,CSS规范中并没有反对这一点。我只担保在任何其他解释器介入之前发送到浏览器的实际HTML、CSS和JavaScript代码。

然而,我也说不,因为我通常测试的每个浏览器实际上都不允许您这样做。

如果您需要自己查看,请将以下文件保存为.html文件,并在主要浏览器中打开它。在我测试的所有浏览器中,JavaScript函数都不能与元素匹配。然而,从id标签中删除任何一个“hunkojunk”都可以正常工作。

示例代码

<html>
<head>
</head>
<body>
    <p id="hunkojunk1 hunkojunk2"></p>

    <script type="text/javascript">
        document.getElementById('hunkojunk2').innerHTML = "JUNK JUNK JUNK JUNK JUNK JUNK";
    </script>
</body>
</html>

其他回答

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

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

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

不。来自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.

任何分配给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>

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

不。每个DOM元素(如果它有id)都有一个唯一的id。你可以用以下方法来近似:

<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>

然后使用导航来得到你真正想要的东西。

如果你只是想应用样式,类名会更好。