为什么拥有多个具有相同id属性的HTML元素是一件坏事? [英] Why is it a bad thing to have multiple HTML elements with the same id attribute?

查看:1399
本文介绍了为什么拥有多个具有相同id属性的HTML元素是一件坏事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在同一页面上有多个具有相同id属性的HTML元素是不好的做法?我正在寻找一种方法来向不熟悉HTML的人解释。

.w3.org / TR / html401 / struct / global.html#h-7.5.2rel =noreferrer>要求id是唯一的,但这听起来不是一个令人信服的理由。为什么我应该关心某人在某个文档中写什么?



我能想到的主要原因是具有相同id的多个元素可能会导致Javascript函数出现奇怪和未定义的行为如document.getElementById。我也知道它可能会导致URL中的片段标识符出现意外的行为。任何人都可以想到任何其他的原因,这对HTML新手来说是有意义的吗?

解决方案

基于你的问题,你已经知道w3c有什么要说的是:

lockquote
id属性为HTML元素指定一个唯一的id(id
属性值必须是唯一的在HTML文档中)。

id属性可用于指向样式表中的样式。



id属性也可以被一个JavaScript(通过HTML DOM)
用来修改具有特定id的HTML元素。


带有id的点是它必须是唯一的。它被用来识别一个元素(或者任何东西:如果两个学生有相同的学生id,学校在看起来会分开)。它不像人名,不一定是唯一的。如果一个数组中的两个元素具有相同的索引,或者两个不同的实数相等......宇宙就会分崩离析。这是身份定义的一部分。



您应该使用class来表达您想要做的事情,我想(ps:你想做什么?)。



希望这有助于!


Why is it bad practice to have more than one HTML element with the same id attribute on the same page? I am looking for a way to explain this to someone who is not very familiar with HTML.

I know that the HTML spec requires ids to be unique but that doesn't sound like a convincing reason. Why should I care what someone wrote in some document?

The main reason I can think of is that multiple elements with the same id can cause strange and undefined behavior with Javascript functions such as document.getElementById. I also know that it can cause unexpected behavior with fragment identifiers in URLs. Can anyone think of any other reasons that would make sense to HTML newbies?

解决方案

Based on your question you already know what w3c has to say about this:

The id attribute specifies a unique id for an HTML element (the id attribute value must be unique within the HTML document).

The id attribute can be used to point to a style in a style sheet.

The id attribute can also be used by a JavaScript (via the HTML DOM) to make changes to the HTML element with the specific id.

The point with an id is that it must be unique. It is used to identify an element (or an anything: if two students had the same student id schools would come apart at the seems). It's not like a human name, which needn't be unique. If two elements in an array had the same index, or if two different real numbers were equal... the universe would just fall apart. It's part of the definition of identity.

You should probably use class for what you are trying to do, I think (ps: what are you trying to do?).

Hope this helps!

这篇关于为什么拥有多个具有相同id属性的HTML元素是一件坏事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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