2
<!DOCTYPE HTML>

<script src='http://code.jquery.com/jquery-latest.min.js'></script>

<body>

<div id='mydiv'>Hello, buddy.</div>
<div id='mydiv'>Hello, friend.</div>

</body>

在 JQuery 中,如果我$('#mydiv')只选择第一个 div,但如果我这样做$('div#mydiv'),它将选择所有这些。

我知道指定元素以及 id 会阻止选择具有相同 id 但不是 div 的其他元素。

这不是一个错误吗?不应该$('#mydiv')选择 id 为“mydiv”的所有元素吗?

4

3 回答 3

4

Explanation for jQuery

Also, in your case, jQuery should select only one element, and the first element for ID. Since you have also given div, it uses getElementsByTagName, and matches the attribute with ID. So, it returns all the instances. Please correct me if I am wrong.

Suggestion

According to web standards, the id attribute must be unique. So, each element should have unique ID. If you want to use things for multiple elements, you have classes.

Also, your HTML won't validate, if you have multiple IDs.

Also, from the XHTML 1.0 Spec

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.

于 2013-01-19T03:07:13.157 回答
4

这根本不是错误... ID (#myId) 不应该在多个实例中使用。这就是我们有类(.myClasses)的原因。

因此,您可以随心所欲地使用类。但是每个 HTML 页面的 ID 始终是唯一的。您可能有一个 ID 显示在许多不同的页面中,但始终作为唯一 ID。

于 2013-01-19T03:04:14.267 回答
2

#mydiv is likely optimized to use getElementById, which is described in the specs as:

Behavior is not defined if more than one element has this id.

Usually the first element with such an ID is returned though.

于 2013-01-19T03:07:35.650 回答