据我所知,有很多方法可以在jQuery中 Select 子元素.

//Store parent in a variable  
var $parent = $("#parent");

Method 1 (by using a scope)

$(".child", $parent).show();

Method 2 (the find() method)

$parent.find(".child").show();

Method 3 (For immediate children only)

$parent.children(".child").show();

Method 4 (via CSS selector)-由@spinon建议

$("#parent > .child").show();

Method 5 (identical to 101)-根据@Kai

$("#parent .child").show();

I'm not familiar with profiling to be able to investigate this on my own, so I would love to see what you have to say.

另外,我知道这可能是this question的复制品,但它不包括所有方法.

推荐答案

Method 1method 2是相同的,唯一的区别是method 1需要解析传递的作用域,并将其转换为对$parent.find(".child").show();的调用.

Method 4Method 5都需要解析 Select 器,然后分别调用:$('#parent').children().filter('.child')$('#parent').filter('.child').

所以method 3总是最快的,因为它需要做最少的工作,并且使用最直接的方法来获得一级子元素.

根据Anurag修订的速度测试:http://jsfiddle.net/QLV9y/1/

Speed test: (More is Better)

On Chrome, Method 3 is the best then method 1/2 and then 4/5

enter image description here

On Firefox, Method 3 is still best then method 1/2 and then 4/5

enter image description here

On Opera, Method 3 is still best then method 4/5 and then 1/2

enter image description here

On IE 8, while slower overall than other browsers, it still follows the Method 3, 1,2,4,5 ordering.

enter image description here

总的来说,method 3是最好使用的方法,因为它被直接调用,它不需要遍历多个级别的子元素,不像方法1/2,也不需要像方法4/5那样解析

不过,请记住,在其中一些 case 中,我们将苹果与橙子进行比较,因为方法5着眼于所有 children ,而不是一级 children .

Jquery相关问答推荐

使用动态类名的gm_addStyle?

Bootstrap 3模态框和video.js视频未正确调整大小

如何向父元素添加类?

为什么函数没有进入

:eq Jquery,我似乎无法显示第一个之后的元素

jQuery.parseJSON 单引号与双引号

了解 Backbone.js REST 调用

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

在不刷新页面的情况下更新网站的 CSS

从 iframe 访问父窗口的元素

如何使div全屏?

如何在 HTML选项标签上显示工具提示?

动态创建并提交表单

jQuery:如何找到第一个可见的输入/ Select /文本区域,不包括按钮?

触发下拉更改事件

将多个 JavaScript 文件合并为一个 JS 文件

使用中键触发 onclick 事件

如何使用 jQuery 的 form.serialize 但排除空字段

AJAX 成功中的 $(this) 不起作用

jQuery / Javascript - 如何将像素值 (20px) 转换为数值 (20)