如果多个不同的 HTML 元素是不同的元素,它们是否可以具有相同的 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5611963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can multiple different HTML elements have the same ID if they're different elements?
提问by omninonsense
Is a scenario like this valid?:
这样的场景有效吗?:
div#foo
span#foo
a#foo
回答by SLaks
No.
不。
Element IDs should be unique within the entire document.
元素 ID 在整个文档中应该是唯一的。
回答by Jin Kim
I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).
我认为某些东西应该是唯一的还是必须是唯一的(即由网络浏览器强制执行)之间存在差异。
Should IDs be unique? YES.
ID 应该是唯一的吗?是的。
Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.
ID 必须是唯一的吗?不,至少 IE 和 FireFox 允许多个元素具有相同的 ID。
回答by mltsy
Can multiple elements have the same ID?
多个元素可以有相同的ID吗?
Yes - whether they are the same tag or not, browsers will render the page even if multiple elements have the same ID.
是的 - 无论它们是否是相同的标签,即使多个元素具有相同的 ID,浏览器也会呈现页面。
Is it Valid HTML?
它是有效的 HTML 吗?
No. This is still true as of the HTML 5.1 spec. However, the spec also says getElementById
must return the firstelement with the given ID, making the behavior not undefined in the case of an invalid document.
不。从HTML 5.1 规范开始,这仍然是正确的。但是,规范还规定getElementById
必须返回具有给定 ID的第一个元素,从而在无效文档的情况下不会未定义行为。
What are the consequences of this type of invalid HTML?
这种类型的无效 HTML 的后果是什么?
Most (if not all) browsers have selected and still doselect the first element with a given ID, when calling getElementById
. Most libraries that find elements by ID inherit this behavior. Most (if not all) browsers also apply styles assigned by id-selectors (e.g. #myid
) to all elements with the specified ID. If this is what you expect and intend, then there are no unintended consequences. If you expect/intend something else (e.g. for all elements with that ID to be returned, or for the style to apply to only one element) then your expectations will not be met and any feature relying on those expectations will fail.
大部分(如果不是全部)的浏览器选择,仍然不选择与给定的ID,打电话时的第一要素getElementById
。大多数通过 ID 查找元素的库都继承了这种行为。大多数(如果不是全部)浏览器也将 id 选择器(例如#myid
)分配的样式应用于具有指定 ID 的所有元素。如果这是您的期望和意图,那么就不会出现意外后果。如果您期望/打算做其他事情(例如,返回具有该 ID 的所有元素,或将样式仅应用于一个元素),那么您的期望将不会得到满足,任何依赖于这些期望的功能都将失败。
Some javascript libraries dohave expectations that are not met when multiple elements have the same ID (see wootscootinboogie's commentabout d3.js)
当多个元素具有相同的 ID 时,某些 javascript 库确实有无法满足的期望(请参阅wootscootinboogie关于 d3.js的评论)
Conclusion
结论
It's best to stick to the standards, but if you know your code works as expected in your current environments, and these IDs are used in a predictable/maintainable way, then there are only 2 practical reasons not to do this:
最好坚持标准,但如果您知道您的代码在当前环境中按预期工作,并且这些 ID 以可预测/可维护的方式使用,那么不这样做的实际原因只有两个:
- To avoid the chance that you are wrong, and one of the libraries you use actually doesmalfunction when multiple elements have the same ID.
- To maintain forward-compatibility of your website/application with libraries or services (or developers!) you may encounter in the future, that do malfunction when multiple elements have the same ID - which is a reasonable possibility since this is not, technically, valid HTML.
- 为了避免出错的机会,并且当多个元素具有相同的 ID 时,您使用的库之一实际上会发生故障。
- 为了保持您的网站/应用程序与库或服务(或开发人员!)的向前兼容性,您将来可能会遇到,当多个元素具有相同的 ID 时会发生故障 - 这是一种合理的可能性,因为这在技术上是无效的HTML。
The power is yours!
权力是你的!
回答by Leniel Maccaferri
Even if the elements are of different types it can cause you some serious problems...
即使元素的类型不同,它也会给你带来一些严重的问题......
Suppose you have 3 buttons with the same id:
假设您有 3 个具有相同 ID 的按钮:
<button id="myid" data-mydata="this is button 1">button 1</button>
<button id="myid" data-mydata="this is button 2">button 2</button>
<button id="myid" data-mydata="this is button 3">button 3</button>
Now you setup some jQuery
code to do something when myid
buttons are clicked:
现在您设置一些jQuery
代码以myid
在单击按钮时执行某些操作:
$(document).ready(function ()
{
$("#myid").click(function ()
{
var buttonData = $(this).data("mydata");
// Call interesting function...
interestingFunction();
$('form').trigger('submit');
});
});
What would you expect? That every button clicked would execute the click event handler setup with jQuery. Unfortunately it won't happen. ONLY the 1stbutton calls the click handler. The other 2 when clicked do nothing. It is as if they weren't buttons at all!
你会期待什么?单击的每个按钮都将使用 jQuery 执行单击事件处理程序设置。不幸的是它不会发生。只有第一个按钮调用点击处理程序。单击其他 2 时什么都不做。就好像它们根本不是按钮一样!
So always assign different IDs
to HTML
elements. This will get you covered against strange things. :)
所以总是分配不同IDs
的HTML
元素。这将使您免受奇怪的事情的困扰。:)
<button id="button1" class="mybtn" data-mydata="this is button 1">button 1</button>
<button id="button2" class="mybtn" data-mydata="this is button 2">button 2</button>
<button id="button3" class="mybtn" data-mydata="this is button 3">button 3</button>
Now if you want the click event handler to run when any of the buttons get clicked it will work perfectly if you change the selector in the jQuery code to use the CSS
class applied to them like this:
现在,如果您希望在单击任何按钮时运行 click 事件处理程序,如果您更改 jQuery 代码中的选择器以使用CSS
应用于它们的类,它将完美地工作,如下所示:
$(document).ready(function ()
{
$(".mybtn").click(function ()
{
var buttonData = $(this).data("mydata");
// Call interesting function...
interstingFunction();
$('form').trigger('submit');
});
});
回答by Gazler
No. two elements with the same id are not valid. IDs are unique, if you wish to do something like that, use a class. Don't forget that elements can have multiple classes by using a space as a delimeter:
不,具有相同 id 的两个元素无效。ID 是唯一的,如果您想做类似的事情,请使用类。不要忘记使用空格作为分隔符,元素可以有多个类:
<div class="myclass sexy"></div>
回答by Nick Steele
The official spec for HTML states that id tags must be unique ANDthe official spec also states that if the render can be completed, it must (i.e. there are no such thing as "errors" in HTML, only "invalid" HTML). So, the following is how id tags actually work in practice. They are all invalid, but still work:
HTML 的官方规范声明 id 标签必须是唯一的,并且官方规范还声明如果渲染可以完成,它必须(即 HTML 中没有“错误”这样的东西,只有“无效”的 HTML)。 因此,以下是 id 标签在实践中的实际工作方式。它们都是invalid,但仍然有效:
This:
这个:
<div id="unique">One</div>
<div id="unique">Two</div>
Renders fine in all browsers. However, document.getElementById only returns an object, not an array; you will only ever be able to select the first div via an id tag. If you were to change the id of the first div using JavaScript, the second ID would then be accessible with document.getElementById (tested on Chrome, FireFox & IE11). You can still select the div using other selection methods, and it's id property will be returned correctly.
在所有浏览器中呈现良好。但是,document.getElementById 只返回一个对象,而不是一个数组;您将只能通过 id 标签选择第一个 div。如果您要使用 JavaScript 更改第一个 div 的 id,则可以使用 document.getElementById 访问第二个 ID(在 Chrome、FireFox 和 IE11 上测试)。您仍然可以使用其他选择方法选择 div,它的 id 属性将被正确返回。
Please notethis above issue opens a potential security vulnerability in sites that render SVG images, as SVGs are allowed to contain DOM elements, and also id tags on them (allows script DOM redirects via uploaded images). As long as the SVG is positioned in the DOM before the element it replaces, the image will receive all JavaScript events meant for the other element.
请注意,上述问题在呈现 SVG 图像的站点中打开了一个潜在的安全漏洞,因为允许 SVG 包含 DOM 元素,以及它们上的 id 标签(允许通过上传的图像进行脚本 DOM 重定向)。只要 SVG 位于 DOM 中它替换的元素之前,图像就会接收到其他元素的所有 JavaScript 事件。
This issue is currently not on anyone's radar as far as I know, yet it's real.
据我所知,这个问题目前没有引起任何人的注意,但它是真实的。
This:
这个:
<div id="unique" id="unique-also">One</div>
Also renders fine in all browsers. However, only the firstid you define this way is utilized, if you tried document.getElementById('unique-also'); in the above example, you would be returned null(tested on Chrome, FireFox & IE11).
在所有浏览器中也能很好地呈现。但是,如果您尝试使用 document.getElementById('unique-also');,则仅使用您以这种方式定义的第一个id。在上面的示例中,您将返回null(在 Chrome、FireFox 和 IE11 上测试)。
This:
这个:
<div id="unique unique-two">Two</div>
Also renders fine in all browsers, however, unlike class tags that can be separated by a space, the id tag allows spaces, so the id of the above element is actually "unique unique-two", and asking the dom for "unique" or "unique-two" in isolation returns nullunless otherwise defined elsewhere in the DOM (tested on Chrome, FireFox & IE11).
在所有浏览器中也可以很好地呈现,但是,与可以用空格分隔的 class 标签不同,id 标签允许有空格,因此上述元素的 id 实际上是“唯一的唯一二”,并要求 dom 为“唯一”除非在 DOM 中的其他地方另有定义(在 Chrome、FireFox 和 IE11 上测试),否则孤立的“unique-two”或“unique-two”返回null。
回答by RobW
SLaks answer is correct, but as an addendum note that the x/html specs specify that all ids must be unique within a (single) html document. Although it's not exactly what the op asked, there could be valid instances where the same id is attached to different entities across multiple pages.
SLaks 的答案是正确的,但作为附录注意,x/html 规范指定所有 ids在(单个)html 文档中必须是唯一的。尽管这不完全是操作员所要求的,但可能存在有效实例,其中相同的 id 附加到跨多个页面的不同实体。
Example:
例子:
(served to modern browsers) article#main-content {styled one way}
(served to legacy) div#main-content {styled another way}
(提供给现代浏览器) article#main-content {以一种方式设计}
(提供给旧版)div#main-content {以另一种方式设计}
Probably an antipattern though. Just leaving here as a devil's advocate point.
不过可能是一个反模式。只是作为恶魔的代言人离开这里。
回答by barrypicker
Well, using the HTML validator at w3.org, specific to HTML5, IDs must be unique
好吧,使用w3.org 上的HTML 验证器,特定于 HTML5,ID 必须是唯一的
Consider the following...
考虑以下...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyTitle</title>
</head>
<body>
<div id="x">Barry</div>
<div id="x">was</div>
<div id="x">here</div>
</body>
</html>
the validator responds with ...
验证器响应...
Line 9, Column 14: Duplicate ID x. <div id="x">was</div>
Warning Line 8, Column 14: The first occurrence of ID x was here. <div id="x">Barry</div>
Error Line 10, Column 14: Duplicate ID x. <div id="x">here</div>
Warning Line 8, Column 14: The first occurrence of ID x was here. <div id="x">Barry</div>
... but the OP specifically stated - what about different element types. So consider the following HTML...
...但OP特别说明 - 不同的元素类型怎么样。因此,请考虑以下 HTML...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyTitle</title>
</head>
<body>
<div id="x">barry
<span id="x">was here</span>
</div>
</body>
</html>
... the result from the validator is...
...验证器的结果是...
Line 9, Column 16: Duplicate ID x. <span id="x">was here</span>
Warning Line 8, Column 14: The first occurrence of ID x was here. <div id="x">barry
Conclusion:
结论:
In either case (same element type, or different element type), if the id is used more than once it is not considered valid HTML5.
在任何一种情况下(相同的元素类型,或不同的元素类型),如果 id 被多次使用,则它不被视为有效的 HTML5。
回答by denishaskin
And for what it's worth, on Chrome 26.0.1410.65, Firefox 19.0.2, and Safari 6.0.3 at least, if you have multiple elements with the same ID, jquery selectors (at least) will return the first element with that ID.
就其价值而言,至少在 Chrome 26.0.1410.65、Firefox 19.0.2 和 Safari 6.0.3 上,如果您有多个具有相同 ID 的元素,jquery 选择器(至少)将返回具有该 ID 的第一个元素。
e.g.
例如
<div id="one">first text for one</div>
<div id="one">second text for one</div>
and
和
alert($('#one').size());
See http://jsfiddle.net/RuysX/for a test.
请参阅http://jsfiddle.net/RuysX/进行测试。
回答by janaravi
I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose
我认为你不能这样做,因为 Id 是独一无二的,你必须将它用于一个元素。您可以为此目的使用类