我知道在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。
当前回答
不。来自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.
其他回答
不。每个DOM元素(如果它有id)都有一个唯一的id。你可以用以下方法来近似:
<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>
然后使用导航来得到你真正想要的东西。
如果你只是想应用样式,类名会更好。
Nay.
从3.2.3.1的id属性:
不能包含空格。
id="a b" <——查找该VaLuE中的空格字符。
也就是说,可以对多个id进行样式化。但如果您遵循规范,答案是否定的。
我的理解一直是:
id是一次性使用的,只应用于一个元素… 每个元素都作为唯一标识符归属于(仅)一个元素。 类可以使用不止一次… 因此,它们可以应用于多个元素,类似但不同的是,每个元素可以有多个类(即多个类)。
不,如果你想沿着那条路径走,你应该使用嵌套的div。此外,即使您可以,想象一下当您运行document.getElementByID()时它会引起的混乱。如果有多个ID,它会抓取哪个ID ?
在稍微相关的主题中,您可以向DIV中添加多个类。
http://meyerweb.com/eric/articles/webrev/199802a.html
ID应该是唯一的,所以您应该在一个页面上只使用特定ID一次。类可以重复使用。
查看HTML id属性(W3Schools)了解更多详细信息。