简体   繁体   English

重复元素子代的ID

[英]repeating id's of element children

Is it ok to have id names for children of an element the same as the ids of children of another element provided the parent id is different? 如果父元素的ID不同,则元素的子元素的ID名称与另一个元素的子元素的ID相同可以吗? Any potential conflict? 有潜在的冲突吗?

No, element id s should be unique throughout the entire document. 不,元素id在整个文档中应该是唯一的。 document.getElementById() won't work right with duplicate id s (obviously, as it only returns one element). document.getElementById()无法与重复的id一起使用(显然,因为它仅返回一个元素)。 Now your page will probably work fine with the duplicate id s, it's not like the browser will crash or refuse to render the page or anything, but it's not correct HTML. 现在,您的页面可能可以使用重复的id正常工作,这不像浏览器会崩溃或拒绝呈现页面或其他任何东西,但这不是正确的HTML。

If you need non-unique identifiers use the class attribute. 如果需要非唯一标识符,请使用class属性。 That's exactly what it's for, to tag multiple elements with the same name. 这就是用相同名称标记多个元素的目的。

Read the spec : 阅读规格

This attribute [id] assigns a name to an element. 此属性[id]为元素分配名称。 This name must be unique in a document. 此名称在文档中必须唯一

It is very bad practice and likely to cause errors. 这是非常不好的做法,并且可能导致错误。 A better solution would be to use classes to distinguish the child objects and then descend from the parent ID to locate the element you are looking for. 更好的解决方案是使用类来区分子对象,然后从父ID下降以找到您要查找的元素。

The ID should always be unique regardless in the context of HTML or Javascript. 无论在HTML还是Javascript的上下文中,ID都应该始终是唯一的。 You are much better off with an unique identifier. 使用唯一的标识符会更好。 For example, you have multiple elements with id named "foo"; 例如,您有多个ID为“ foo”的元素。 in document.getElementById("foo") will only return the first instance by that id. document.getElementById(“ foo”)中的ID将仅返回该ID的第一个实例。

如果您具有相同ID的不同DOM元素,则有时会导致麻烦……甚至以为它可能会起作用就不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM