我从谷歌的AdWords网站上获取数据,该网站有多个元素,相同的id个元素.

Could you please explain why the following 3 queries doesn't result with the same answer (2)?

Live Demo

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.

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.

但是,在同一个页面上不应该有两个具有相同ID的元素.如果您的CSS需要两个元素,请使用一个类来代替.


如果绝对必须按重复ID Select ,请使用属性 Select 器:

$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

Note:如果可能,您应该使用标记 Select 器来限定该 Select 器,如下所示:

$('span[id="a"]');

Jquery相关问答推荐

如何使用 jQuery 强制悬停状态?

Flask,如何为ajax调用返回成功状态码

jQuery ajax() 使用成功、错误和完成与 .done()、.fail() 和 always()

jquery - 单击事件不适用于动态创建的按钮

找到下一个匹配的sibling 姐妹的有效,简洁的方法?

jQuery获取表单字段值

调整浏览器大小时调整jqGrid的大小?

scrollIntoView 是否适用于所有浏览器?

试图检测浏览器关闭事件

如何使用 jQuery Select sibling 元素?

动画元素变换旋转

$.each(selector) 和 $(selector).each() 有什么区别

为什么找不到我的 json 文件?

一组元素中具有最大高度的元素

查找 id 以开头的 html 元素

使用 Jquery 查找父 div 的 id

jQuery位置href

jQuery 发送字符串作为 POST 参数

带有 LIKE 的 Spring JPA @Query

将变量的值复制到另一个