对多个HTML标记使用相同的ID?

gau*_*hor 7 html css css-selectors

可能重复:
具有相同ID的多个元素响应一个CSS ID选择器

下面是我测试的示例代码,我感到困惑.每个人都说我们可以使用或者我们应该每个id只使用一次,但我有睾丸使用它多次,但它给了我正确的输出.

我该怎么办?

在这个例子中,对我来说,它类似于类

码:

<html>
<head>
<style>

#exampleID1 { background-color: blue; } 
#exampleID2 { text-transform: uppercase; } 

</style>
</head>
<body>
<p id="exampleID1">This paragraph has an ID name of "exampleID1" and has a blue CSS defined background.</p>
<p id="exampleID2">This paragraph has an ID name of "exampleID2" and has had its text transformed to uppercase letters.</p>

<address id="exampleID1">

Written by W3Schools.com<br />
<a href="mailto:us@example.org">Email us</a><br />
Address: Box 564, Disneyland<br />
Phone: +12 34 56 78
</address>


<blockquote id="exampleID1">
Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.
</blockquote>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

请看上面的代码并回答我为什么我们不应该在页面中使用id选择器两次,而它的工作正常.

Que*_*tin 17

id必须在页面中是唯一的.如果要描述一组元素,请使用类.

为什么我们不应该在页面中使用id选择器两次,而它的工作正常.

您正在制作错误,并且取决于将查看页面以补偿它的每个浏览器.你不能确定他们都会.


Mar*_*ato 6

我认为更容易理解的方法是对产品进行类比.想象一下,ID像序列号这样的作品,换句话说,它必须是唯一的,这样你就可以识别出具有数百万份相同副本的产品.

然后,想象一下class作为产品代码,可以是条形码例如.在超市中,所有相同的产品都具有相同的条形码,可由光学读取器读取.

因此,a ID是一个独特的标识符,并将一class组元素分组.

但如果我ID在我的HTML/CSS中使用相同的结果,我会得到一个完美的结果,为什么我要担心独特ID的?

原因1:

将来,如果您需要使用Javascript,并且如果您需要操作特定元素并且它具有重复项ID,则您的代码将不会生成预期结果.

原因2

W3C不会对您的代码进行验证,这意味着您可能会对浏览器中的网站兼容性感到头痛.它可以在一个浏览器中正常工作,而在其他浏

使用一个真实的例子,想象你想要使用Javascript,这个元素的文本以dinamically方式更新:

<blockquote id="exampleID1">
Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.
</blockquote>
Run Code Online (Sandbox Code Playgroud)

使用Javascript/JQuery,您将使用如下代码:

$("#exampleID1").html("Changing element content");
Run Code Online (Sandbox Code Playgroud)

然后元素的文本<blockquote id="exampleID1">将被更新,但是下面的元素也会更新,因为它具有相同的元素ID.

<p id="exampleID1">This paragraph has an ID name of "exampleID1" and has a blue CSS defined background.</p>
Run Code Online (Sandbox Code Playgroud)

因此,如果您只想更新一个元素,它们必须具有唯一的IDs.

我希望你能用这个解释来更好地理解ID和之间的区别class.