我知道在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。
当前回答
I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say "sysadm" and "team coordinator" having the id="sysadm teamcoordinator" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(
其他回答
No.
话虽如此,没有什么能阻止你这么做。但是不同的浏览器会产生不一致的行为。不要这样做。每个元素一个ID。
如果需要对一个元素进行多个赋值,请使用classes(用空格分隔)。
我想说技术上是可以的,因为真正呈现的内容在技术上总是依赖于浏览器。大多数浏览器都尽可能地遵循规范,据我所知,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的另一个元素交叉。如果你不做,那就没有意义,如果你做了,那也没什么意义。
不,单个标记不能有多个id,但我见过带有name属性和id属性的标记,一些应用程序对它们的处理是相同的。
每个元素只能有一个ID,但确实可以有多个类。但不要有多个类属性;将多个类值放入一个属性中。
<div id="foo" class="bar baz bax">
完全合法。