当多个元素具有相同的 ID 值时,jQuery 如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8498579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does jQuery work when there are multiple elements with the same ID value?
提问by Misha Moroshko
I fetch data from Google's AdWords website which has multiple elements with the same id
.
我从 Google 的 AdWords 网站获取数据,该网站具有多个具有相同id
.
Could you please explain why the following 3 queries doesn't result with the same answer (2)?
您能否解释为什么以下 3 个查询没有得到相同的答案 (2)?
HTML:
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
回答by Joseph Silber
Having 2 elements with the same ID is not valid html according to the W3C specification.
根据 W3C 规范,具有相同 ID 的 2 个元素不是有效的 html。
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.
当您的 CSS 选择器只有一个 ID 选择器(并且不在特定上下文中使用)时,jQuery 使用本机document.getElementById
方法,该方法仅返回具有该 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.
然而,在其他两个实例中,jQuery 依赖于 Sizzle 选择器引擎(或querySelectorAll
,如果可用),它显然选择了两个元素。结果可能因浏览器而异。
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.
但是,您永远不应该在同一页面上有两个具有相同 ID 的元素。如果您的 CSS 需要它,请改用类。
If you absolutely must select by duplicate ID, use an attribute selector:
如果您绝对必须通过重复 ID 进行选择,请使用属性选择器:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
看看小提琴:http: //jsfiddle.net/P2j3f/2/
Note:if possible, you should qualify that selector with a tag selector, like this:
注意:如果可能,您应该使用标签选择器来限定该选择器,如下所示:
$('span[id="a"]');
回答by jfriend00
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.
应该只有一个具有给定 id 的元素。如果您遇到这种情况,请参阅我的答案的第二部分以了解选项。
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.
当您有多个具有相同 id 的元素(非法 HTML)时,浏览器的行为不是由规范定义的。您可以测试所有浏览器并找出它们的行为方式,但使用此配置或依赖任何特定行为是不明智的。
Use classes if you want multiple objects to have the same identifier.
如果您希望多个对象具有相同的标识符,请使用类。
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
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.
如果您想可靠地查看 ID 相同的元素,因为您无法修复文档,那么您将不得不进行自己的迭代,因为您不能依赖任何内置的 DOM 函数。
You could do so like this:
你可以这样做:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
或者,使用 jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
jQuery 工作示例: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 used document.getElementById("a")
. If the selector is more complex than that and querySelectorAll()
exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll()
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 own querySelectorAll()
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 中,您可以研究代码以找出任何给定版本在做什么,但由于这是非法的 HTML,因此不能保证它会随着时间的推移保持不变。从我在 jQuery 中看到的,它首先检查选择器是否是一个简单的 id #a
,如果是,则只使用document.getElementById("a")
. 如果选择器比这更复杂并且querySelectorAll()
存在,jQuery 通常会将选择器传递给内置的浏览器函数,该函数将具有特定于该浏览器的实现。如果querySelectorAll()
不存在,那么它将使用 Sizzle 选择器引擎手动查找将拥有自己实现的选择器。因此,您可以在同一浏览器系列中至少拥有三种不同的实现,具体取决于确切的选择器和浏览器的新程度。然后,各个浏览器都有自己的querySelectorAll()
实现。如果您想可靠地处理这种情况,您可能必须使用自己的迭代代码,如我上面所示。
回答by Aaron
jQuery's id
selector only returns one result. The descendant
and multiple
selectors in the second and third statements are designed to select multiple elements. It's similar to:
jQuery 的id
选择器只返回一个结果。第二条和第三条语句中的descendant
andmultiple
选择器旨在选择多个元素。它类似于:
Statement 1
声明 1
var length = document.getElementById('a').length;
...Yields one result.
...产生一个结果。
Statement 2
声明 2
var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
if (document.body.childNodes.item(i).id == 'a') {
length++;
}
}
...Yields two results.
...产生两个结果。
Statement 3
声明 3
var length = document.getElementById('a').length + document.getElementsByTagName('div').length;
...Also yields two results.
...也产生两个结果。
回答by Ralph Lavelle
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.
每个 id 值在一个文档中只能使用一次。如果多个元素被分配了相同的 ID,则使用该 ID 的查询将只选择 DOM 中第一个匹配的元素。但是,不应依赖这种行为;具有多个元素使用相同 ID 的文档是无效的。
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.
淘气的谷歌。但他们甚至没有关闭他们的<html>
和<body>
我听到的标签。问题是,为什么 Misha 的第二个和第三个查询也返回 2 而不是 1。
回答by Baqer Naqvi
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.
如果您有多个具有相同 id 或相同名称的元素,只需为这些多个元素分配相同的类并通过索引访问它们并执行所需的操作。
<div>
<span id="a" class="demo">1</span>
<span id="a" class="demo">2</span>
<span>3</span>
</div>
JQ:
江青:
$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");
回答by Héctor Lazarte
Everybody says "Each id value must be used only once within a document", but 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 JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this
每个人都说“每个 id 值只能在一个文档中使用一次”,但是当我们有一个愚蠢的页面有多个具有相同 id 的元素时,我们如何获取所需的元素。如果我们使用 JQuery '#duplicatedId' 选择器,我们只会得到第一个元素。要实现选择其他元素,您可以执行以下操作
$("[id=duplicatedId]")
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId
您将获得一个包含 id=duplicatedId 的所有元素的集合
回答by Ravindra Dhage
you can simply write $('span#a').length to get the length.
你可以简单地写 $('span#a').length 来得到长度。
Here is the Solution for your code:
这是您的代码的解决方案:
console.log($('span#a').length);
try JSfiddle: https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/
试试 JSfiddle:https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/