简体   繁体   English

具有相同ID的多个元素

[英]multiple elements with the same id

i've heard using multiple id attributes is very bad practice but what confuses me is what if the elements are nested like this... 我听说使用多个id属性是非常不好的做法,但令我困惑的是,如果元素像这样嵌套,该怎么办...

<div id="slideshow1" class="slideshow">
    <div id="left" class="slideshow-arrow"></div>
    <div id="right" class="slideshow-arrow"></div>
</div>
<div id="slideshow2" class="slideshow">
    <div id="left" class="slideshow-arrow"></div>
    <div id="right" class="slideshow-arrow"></div>
</div>

i've made an example with js here and everything seems to work fine.. 我在这里用js作了一个例子,似乎一切正常。

http://jsfiddle.net/6YPsX/ http://jsfiddle.net/6YPsX/

if they were nested within the same element then unique id's would make sense but do ID's really need to be unique to the whole document? 如果它们嵌套在同一个元素中,那么唯一的ID是有意义的,但是ID真的需要在整个文档中是唯一的吗?

An ID is more than just a way of finding an element, there are other things associated with an ID. ID不仅仅是一种查找元素的方法,ID还有其他关联。 The following link should be helpful and provide a greater insight into this. 以下链接应该会有所帮助,并且可以对此提供更深入的了解。 Here are the main points: 这里是要点:

The id attribute has several roles in HTML: id属性在HTML中具有多个角色:

  • As a style sheet selector. 作为样式表选择器。 As a target anchor for hypertext links. 作为超文本链接的目标锚点。
  • As a means to reference a particular element from a script. 作为从脚本中引用特定元素的一种方式。
  • As the name of a declared OBJECT element. 作为已声明的OBJECT元素的名称。
  • For general purpose processing by user agents (eg for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.). 用于用户代理的通用处理(例如,用于在将数据从HTML页面提取到数据库中,将HTML文档转换成其他格式等时标识字段)。

link to w3 site 链接到W3网站

You can have multiple classes on the same element 您可以在同一元素上具有多个类

<div id="slideshow1" class="slideshow">
    <div class="slideshow-arrow left"></div>
    <div class="slideshow-arrow right"></div>
</div>

CSS 的CSS

.slideshow-arrow {
    background: none top left no-repeat;
    width: 20px;
    height: 20px;
}
.slideshow-arrow.left {
    background-image: url('...');
}
.slideshow-arrow.right {
    background-image: url('...');
}

It is a bad practice it won't pass W3C validation and it get's even worse when you try to implement JavaScript. 这是一个不好的做法,它不会通过W3C验证,并且在尝试实现JavaScript时会变得更糟。 Just use a class name instead or give them different id names. 只需使用类名代替或给他们提供不同的ID名称即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM