当多个元素具有相同的 ID 值时,jQuery 如何工作?
我从 Google 的 AdWords 网站获取数据,该网站包含多个具有相同 id
的元素。
您能否解释一下为什么以下 3 个查询没有得到相同的答案 (2)?
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
I fetch data from Google's AdWords website which has multiple elements with the same id
.
Could you please explain why the following 3 queries doesn't result with the same answer (2)?
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
根据 W3C 规范,具有相同 ID 的 2 个元素不是有效的 html。
当您的 CSS 选择器只有 ID 选择器(并且不在特定上下文中使用)时,jQuery 使用本机
document.getElementById
方法,该方法仅返回具有该 ID 的第一个元素。然而,在其他两个实例中,jQuery 依赖于 Sizzle 选择器引擎(或
querySelectorAll
,如果可用),它显然会选择这两个元素。结果可能因浏览器而异。但是,同一页面上永远不应该有两个具有相同 ID 的元素。如果您的 CSS 需要它,请改用类。
如果您绝对必须通过重复 ID 选择,请使用属性选择器:
看一下小提琴: http:// jsfiddle.net/P2j3f/2/
注意: 如果可能,您应该使用类型选择器限定该选择器,如下所示:
这样做的原因是类型选择器效率更高比属性选择器。如果您使用类型选择器限定属性选择器,jQuery 将首先使用类型选择器来查找该类型的元素,然后仅在这些元素上运行属性选择器。这简直是效率更高了。
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native
document.getElementById
method, which returns only the first element with that ID.However, in the other two instances, jQuery relies on the Sizzle selector engine (or
querySelectorAll
, if available), which apparently selects both elements. Results may vary on a per browser basis.However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a type selector, like this:
The reason for this is because a type selector is much more efficient than an attribute selector. If you qualify your attribute selector with a type selector, jQuery will first use the type selector to find the elements of that type, and then only run the attribute selector on those elements. This is simply much more efficient.
应该只有一个具有给定 id 的元素。如果您遇到这种情况,请参阅我答案的第二部分以获取选项。
规范未定义当多个元素具有相同 id(非法 HTML)时浏览器的行为方式。您可以测试所有浏览器并找出它们的行为方式,但使用此配置或依赖任何特定行为是不明智的。
如果您希望多个对象具有相同的标识符,请使用类。
如果您因为无法修复文档而想要可靠地查看具有相同 ID 的元素,那么您将必须进行自己的迭代,因为您不能依赖任何内置 DOM 函数。
你可以这样做:
或者,使用 jQuery:
jQuery 工作示例: http://jsfiddle.net/jfriend00/ XY2tX/。
至于为什么会得到不同的结果,这与执行实际选择器操作的任何代码片段的内部实现有关。在 jQuery 中,您可以研究代码以找出任何给定版本正在执行的操作,但由于这是非法 HTML,因此无法保证它会随着时间的推移保持不变。从我在 jQuery 中看到的来看,它首先检查选择器是否是像
#a
这样的简单 id,如果是,则仅使用document.getElementById("a").如果选择器比这更复杂并且存在
querySelectorAll()
,jQuery 通常会将选择器传递给内置浏览器函数,该函数将具有特定于该浏览器的实现。如果querySelectorAll()
不存在,那么它将使用 Sizzle 选择器引擎手动查找将拥有自己的实现的选择器。因此,您可以在同一浏览器系列中拥有至少三种不同的实现,具体取决于确切的选择器和浏览器的新程度。然后,各个浏览器都将拥有自己的querySelectorAll()
实现。如果您想可靠地处理这种情况,您可能必须使用自己的迭代代码,如我上面所示。There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
Or, using jQuery:
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like
#a
and if so, just useddocument.getElementById("a")
. If the selector is more complex than that andquerySelectorAll()
exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. IfquerySelectorAll()
does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their ownquerySelectorAll()
implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.jQuery 的
id
选择器仅返回一个结果。第二个和第三个语句中的后代选择器和多个选择器旨在选择多个元素。它类似于:语句 1
...产生一个结果。
语句 2
...产生两个结果。
语句 3
...也产生两个结果。
jQuery's
id
selector only returns one result. Thedescendant
andmultiple
selectors in the second and third statements are designed to select multiple elements. It's similar to:Statement 1
...Yields one result.
Statement 2
...Yields two results.
Statement 3
...Also yields two results.
当我们有一个愚蠢的页面,其中包含多个具有相同 ID 的元素时,我们该如何获取所需的元素呢?如果我们使用“#duplicateId”,我们只能得到第一个元素。要实现选择其他元素,您可以执行以下操作:
您将获得一个包含 id=duplicateId 的所有元素的集合。
What we do to get the elements we need when we have a stupid page that has more than one element with same ID? If we use '#duplicatedId' we get the first element only. To achieve selecting the other elements you can do something like this:
You will get a collection with all elements with id=duplicatedId.
从 id 选择器 jQuery 页面:
每个 id 值只能在一个文档。如果多个元素被分配了相同的 ID,则使用该 ID 的查询将仅选择 DOM 中第一个匹配的元素。然而,不应依赖这种行为;具有多个使用相同 ID 的元素的文档是无效的。
淘气的 Google。但他们甚至没有关闭我听到的
和
标签。但问题是,为什么 Misha 的第二个和第三个查询返回 2 而不是 1。
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their
<html>
and<body>
tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.如果您有多个具有相同 id 或相同名称的元素,只需为这些多个元素分配相同的类并通过索引和访问它们即可。执行您所需的操作。
杰Q:
If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.
JQ:
访问单个项目
Access individual item
您可以简单地编写 $('span#a').length 来获取长度。
这是您的代码的解决方案:
尝试 JSfiddle:
https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/
you can simply write $('span#a').length to get the length.
Here is the Solution for your code:
try JSfiddle:
https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/