问题描述
我从Google的AdWords网站获取数据,该网站包含多个具有相同id
的元素.
I fetch data from Google's AdWords website which has multiple elements with the same id
.
您能否解释为什么以下3个查询没有得到相同答案(2)?
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
});
推荐答案
根据W3C规范,具有2个具有相同ID的元素不是有效的html.
Having 2 elements with the same ID is not valid html according to the W3C specification.
当您的CSS选择器仅具有一个ID选择器(并且未在特定上下文中使用)时,jQuery使用本机的document.getElementById
方法,该方法仅返回具有该ID的第一个元素.
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.
但是,在其他两个实例中,jQuery依赖于Sizzle选择器引擎(或querySelectorAll
,如果可用),该引擎显然选择了两个元素.结果可能因浏览器而异.
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.
但是,在同一页面上绝对不能有两个具有相同ID的元素.如果您的CSS需要它,请改用一个类.
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进行选择,请使用属性选择器:
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
看看小提琴: http://jsfiddle.net/P2j3f/2/
注意:如果可能的话,您应该使用标签选择器来限定该选择器,如下所示:
Note: if possible, you should qualify that selector with a tag selector, like this:
$('span[id="a"]');
这篇关于当多个具有相同"id"的元素时,jQuery如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!