多个具有相同 ID 的元素响应一个 CSS ID 选择器 [英] Several elements with the same ID responding to one CSS ID selector

查看:31
本文介绍了多个具有相同 ID 的元素响应一个 CSS ID 选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

让我们阅读 w3.org 文档:

使 ID 类型的属性与众不同的是,没有两个这样的属性属性可以具有相同的值;无论文档语言是什么,ID 属性可用于唯一标识其元素.

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 的 2 个元素的示例在所有浏览器中都可以正常工作,尽管它无效:

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

#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?

推荐答案

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

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.

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

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

例如:

document.getElementById('red');

只会给你第一个.

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

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 assume that it'll work.

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

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...

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

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

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

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

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

这篇关于多个具有相同 ID 的元素响应一个 CSS ID 选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆