$(“#id”)只选择第一个元素,但$(“div#id”)选择两者? [英] $("#id") only selects the first element but $("div#id") selects both?

查看:394
本文介绍了$(“#id”)只选择第一个元素,但$(“div#id”)选择两者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!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'),它会选择所有的。

When in JQuery, if I $('#mydiv') it will select only the first div, BUT if I do $('div#mydiv') it will select all of them.

我理解指定元素以及id,它将防止选择具有相同id但不是div的其他元素。

I understand that specifying the element as well as the id, it will prevent from selecting other elements that have the same id but are not divs.

这不是一个bug吗?不应 $('#mydiv')选择所有元素的id是'mydiv'?

Isn't this a bug? Shouldn't $('#mydiv') select all elements which id is 'mydiv'?

推荐答案

jQuery的说明



此外,在你的情况下,jQuery应该只选择一个元素,第一个元素 ID 。由于您还给了 div ,它使用 getElementsByTagName ,并将该属性与ID匹配。所以,它返回所有的实例。

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.

根据网络标准, id 属性必须是唯一的。因此,每个元素应该有唯一的ID。

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.

此外,如果您有多个ID,您的HTML将无法验证。

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

此外,从 XHTML 1.0规范


在XML中,片段标识符是
类型ID,并且只能有一个
单个属性类型ID每
元素。因此,在XHTML 1.0中,
id属性被定义为类型
ID。为了确保XHTML 1.0
文档是结构良好的XML
文档,XHTML 1.0文档MUST
在元素上定义
片段标识符时使用id属性
以上所列。请参阅HTML
兼容性指南
确保此类锚点的信息
在服务
时向后兼容XHTML文档作为媒体类型
text / html。

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.

这篇关于$(“#id”)只选择第一个元素,但$(“div#id”)选择两者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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