在jQuery中选择后代元素的最快方法是什么? [英] What is the fastest method for selecting descendant elements in jQuery?

查看:82
本文介绍了在jQuery中选择后代元素的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在 jQuery 中有多种选择子元素的方法.

As far is I know, there are a number of ways of selecting child elements in jQuery.

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

方法1 (通过使用范围)

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

方法2 (find()方法)

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

方法3 (仅适用于直系子女)

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

方法4 (通过CSS选择器)-@spinon建议

Method 4 (via CSS selector) - suggested by @spinon

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

方法5 (与方法2 相同)-根据@Kai

Method 5 (identical to Method 2) - according to @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.

P.S.我了解这可能是此问题的重复副本,但是它并不涵盖所有方法.

P.S. I understand this is a possible duplicate of this question but it doesn't cover all methods.

推荐答案

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

Method 1 and method 2 are identical with the only difference is that method 1 needs to parse the scope passed and translate it to a call to $parent.find(".child").show();.

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

Method 4 and Method 5 both need to parse the selector and then just call: $('#parent').children().filter('.child') and $('#parent').filter('.child') respectively.

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

So method 3 will always be the fastest because it needs to do the least amount of work and uses the most direct method to get first-level children.

基于此处的Anurag修订后的速度测试: http://jsfiddle.net/QLV9y/1/

Based on Anurag's revised speed tests here: http://jsfiddle.net/QLV9y/1/

速度测试:(越多越好)

Speed test: (More is Better)

Chrome 上,方法3最好,然后是方法1/2,然后是4/5

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

Firefox 上,方法3仍然是最佳方法,然后是方法1/2和4/5

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

Opera 上,方法3仍然是最好的,然后是方法4/5然后是1/2

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

IE 8 上,虽然总体上比其他浏览器要慢,但它仍然遵循方法3、1、2、4、5的顺序.

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

总体而言,方法3 是总的最佳使用方法,因为它直接被调用,与方法1/2不同,它不需要遍历一个以上的子元素级别,并且它不需要像方法4/5一样需要解析

Overall, method 3 is the overal best method to use as it is called directly and it doesn't need to traverse more than one level of child elements unlike method 1/2 and it doesn't need to be parsed like method 4/5

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

Though, keep in mind that in some of these we are comparing apples to oranges as Method 5 looks at all children instead of first-level ones.

这篇关于在jQuery中选择后代元素的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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