本文介绍了具有相同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.

让我们阅读:

具有相同ID的元素在所有浏览器中都可正常工作,但它无效:

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

推荐答案

浏览器总是试图默默失败。这意味着,即使您的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选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 15:08