当多个具有相同ID值的元素时,jQuery如何工作? [英] How does jQuery work when there are multiple elements with the same ID value?

查看:96
本文介绍了当多个具有相同ID值的元素时,jQuery如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从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
});


推荐答案

具有2个具有相同ID的元素无效html根据W3C规范。

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如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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