1

我听说使用多个 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>

我在这里用js做了一个例子,一切似乎都很好..

http://jsfiddle.net/6YPsX/

如果它们嵌套在同一个元素中,那么唯一的 id 是有意义的,但是 ID 真的需要对整个文档是唯一的吗?

4

3 回答 3

3

An ID is more than just a way of finding an element, there are other things associated with an 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:

  • 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.
  • For general purpose processing by user agents (e.g. for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.).

link to w3 site

于 2013-11-13T14:50:18.290 回答
2

你可以在同一个元素上有多个类

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

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('...');
}
于 2013-11-13T14:48:25.663 回答
1

这是一种不好的做法,它不会通过 W3C 验证,当您尝试实现 JavaScript 时,情况会变得更糟。只需使用类名或给他们不同的 id 名称。

于 2013-11-13T14:46:30.113 回答