Html 多个具有相同 ID 的元素响应一个 CSS ID 选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7262195/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:22:54  来源:igfitidea点击:

Several elements with the same ID responding to one CSS ID selector

htmlcsscss-selectors

提问by Webars

Is it safe to give several elements the same ID in one page? For example this often happens, when using some jquery plugins, when you run some slider or gallery twice or more. We know, developers like to give some ID to the html container in order the script works faster.

在一页中为多个元素提供相同的 ID 是否安全?例如,当使用某些 jquery 插件时,当您运行某个滑块或图库两次或更多次时,经常会发生这种情况。我们知道,开发人员喜欢为 html 容器提供一些 ID,以便脚本更快地运行。

Let's read w3.org documentation:

让我们阅读w3.org 文档

What makes attributes of type ID special is that no two such attributes can have the same value; whatever the document language, an ID attribute can be used to uniquely identify its element.

ID 类型属性的特殊之处在于,没有两个这样的属性可以具有相同的值;无论文档语言如何,ID 属性都可用于唯一标识其元素。

But the next example with 2 elements having the same ID works fine in all browsers, though it's not valid:

但是下一个具有相同 ID 的 2 个元素的示例在所有浏览器中都可以正常工作,尽管它无效:

#red {
  color: red;
}
<p id="red">I am a red text.</p>
<p id="red">I am a red text too.</p>

Can anybody explain this strange situation?

有人能解释一下这种奇怪的情况吗?

回答by Joseph Silber

Browsers always try to "fail silently". What this means is that even though your HTML is invalid, the browser will try to guess what your intent was, and handle it accordingly.

浏览器总是试图“静默失败”。这意味着即使您的 HTML 无效,浏览器也会尝试猜测您的意图,并相应地处理它。

However, deviating from the spec can cause some very unforeseen side effects.

然而,偏离规范可能会导致一些非常不可预见的副作用。

For example:

例如:

document.getElementById('red');

will only get you the first one.

只会给你第一个。

You'll also have to test your page in all the browsers that your users might use, to make sure your code works as intended. You can't just assumethat it'll work.

您还必须在用户可能使用的所有浏览器中测试您的页面,以确保您的代码按预期工作。你不能只是假设它会起作用。

In short:Don't do this! If you need to target several elements with the same CSS, use a class name. That's what they were designed for...

简而言之:不要这样做!如果您需要使用相同的 CSS 定位多个元素,请使用类名。这就是它们的设计目的...



Having said that; if you reallyneed to select multiple elements with the same ID, use an attribute selector:

话说回来; 如果您确实需要选择具有相同 ID 的多个元素,请使用属性选择器:

document.querySelectorAll('p[id="red"]');

Note however, that this doesn't work in IE7 and below...

但是请注意,这在 IE7 及以下版本中不起作用......

回答by BoltClock

Is it safe to give several elements the same ID in one page?

在一页中为多个元素提供相同的 ID 是否安全?

As you know, it's against the validation rules to give more than one element the same ID in a single page. However, rules are broken, and in the world of HTML tag soup, browsers have to account for these broken rules without breaking pages, hence the behavior you observe.

如您所知,在单个页面中为多个元素提供相同 ID 是违反验证规则的。然而,规则是被破坏的,在 HTML 标签汤的世界中,浏览器必须在不破坏页面的情况下解释这些被破坏的规则,因此你观察到的行为。

Although browsers have been shown to behave the same way even if you do so (fortunately for situations where it can't be helped), I wouldn't call it totally "safe" to do so, as such behavior may not be consistent or reliable.

尽管即使您这样做,浏览器也表现出相同的行为(幸运的是在无法帮助的情况下),但我不会称这样做完全“安全”,因为这种行为可能不一致或可靠的。

The best bet is to follow the rules as faithfully as you can, and only break the rules if you have very, very good reasons to (and you almost never will, so don't even consider it). Otherwise, like Joseph Silber said, use classes, designed specifically for classifying or grouping multiple elements.

最好的办法是尽可能忠实地遵守规则,并且只有在你有非常非常好的理由时才违反规则(而且你几乎永远不会这样做,所以甚至不要考虑它)。否则,就像 Joseph Silber 所说的那样,使用专为对多个元素进行分类或分组而设计的类。

Can anybody explain this strange situation?

有人能解释一下这种奇怪的情况吗?

The uniqueness of IDs in an HTML document is not enforced or assumed by CSS; instead, the Selectors specsimply states this:

HTML 文档中 ID 的唯一性不是由 CSS 强制或假定的;相反,选择器规范只是简单地说明了这一点:

An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector.

ID 选择器表示具有与 ID 选择器中的标识符相匹配的标识符的元素实例。

Notice the use of the word "an" throughout this sentence.

请注意在整个句子中使用了“an”一词。

Following that statement are some example uses, which use the word "any" instead:

在该语句之后是一些示例用法,它们使用单​​词“any”代替:

The following ID selector represents any element whose ID-typed attribute has the value "chapter1":

#chapter1

The following selector represents any element whose ID-typed attribute has the value "z98y".

*#z98y

以下 ID 选择器表示其 ID 类型属性值为“chapter1”的任何元素:

#chapter1

以下选择器表示其 ID 类型属性值为“z98y”的任何元素。

*#z98y

The assumption of a conformant document is clarified by level 3 of the Selectors spec, near the beginning of the section (emphasis mine):

选择器规范的第 3 级在本节开头附近(重点是我的)澄清了符合文档的假设:

What makes attributes of type ID special is that no two such attributes can have the same value in a conformant document, regardless of the type of the elements that carry them; whatever the document language, an ID typed attribute can be used to uniquely identify its element.

ID 类型属性的特殊之处在于,在一个符合文档中,没有两个这样的属性可以具有相同的值,无论携带它们的元素是什么类型;无论文档语言如何,ID 类型属性都可用于唯一标识其元素。

Where "conformant" refers to conformance to HTML, not CSS. Keep in mind that this text wasn't present in the level 2 spec, which is the one you quote in your question.

其中“符合”是指符合 HTML,而不是 CSS。请记住,此文本未出现在级别 2 规范中,这是您在问题中引用的内容。

Bear in mind that the text that is quoted is not normative. While it's a way of helping implementers work out error-handling cases, it's not a compulsory rule to be followed, and indeed, any implementation is free to behave differently without being in violation of the spec. Don't write invalid HTML just to take advantage of what may seem to be expected or consistent behaviors, because you can't guarantee that these behaviors will remain that way. Any CSS implementation is free to match elements sharing the same ID differently, or even stop matching them altogether, if it decides that's how it should handle documents that break this rule.

请记住,引用的文本不是规范性的。虽然它是帮助实现者解决错误处理案例的一种方式,但它不是必须遵循的强制性规则,实际上,任何实现都可以自由地以不同的方式表现,而不会违反规范。不要仅仅为了利用看似预期或一致的行为而编写无效的 HTML,因为您无法保证这些行为会保持这种状态。任何 CSS 实现都可以自由地以不同的方式匹配共享相同 ID 的元素,甚至完全停止匹配它们,如果它决定应该如何处理违反此规则的文档。

In other words: just because you can, doesn't mean you should.

换句话说:仅仅因为你可以,并不意味着你应该。

回答by Rupert Horlick

This works with simple HTML styling but will not work with queries.

这适用于简单的 HTML 样式,但不适用于查询。

From the jQuery API documentation:

来自jQuery API 文档

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

每个 id 值在一个文档中只能使用一次。如果多个元素被分配了相同的 ID,则使用该 ID 的查询将只选择 DOM 中第一个匹配的元素。但是,不应依赖这种行为;具有多个元素使用相同 ID 的文档是无效的。