在 jQuery 中选择后代元素的最快方法是什么? [英] What is the fastest method for selecting descendant elements in jQuery?
问题描述
据我所知,在 jQuery 中有多种选择子元素的方法.
//将父级存储在一个变量中var $parent = $("#parent");
方法 1 (通过使用范围)
$(".child", $parent).show();
方法 2 (find() 方法)
$parent.find(".child").show();
方法 3 (仅适用于直系儿童)
$parent.children(".child").show();
方法 4 (通过 CSS 选择器) - 由 @spinon 建议
$("#parent > .child").show();
方法 5 (与方法 2 相同) - 根据 @Kai
$("#parent .child").show();
我不熟悉分析,无法自行调查,所以我很想看看您要说什么.
附言我知道这可能是
在 Firefox 上,方法 3 仍然是最好的,然后是方法 1/2,然后是方法 4/5
在Opera上,方法3仍然是最好的,然后是方法4/5,然后是方法1/2
在 IE 8 上,虽然总体上比其他浏览器慢,但它仍然遵循方法 3、1、2、4、5 的顺序.
总体而言,方法 3 是总体上最好的方法,因为它是直接调用的,与方法 1/2 不同,它不需要遍历多于一层的子元素,并且它不需要t 需要像方法 4/5 那样解析
不过,请记住,在其中的一些中,我们将苹果与橙子进行比较,因为方法 5 着眼于所有孩子,而不是第一级孩子.
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");
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) - suggested by @spinon
$("#parent > .child").show();
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. I understand this is a possible duplicate of this question but it doesn't cover all methods.
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();
.
Method 4 and Method 5 both need to parse the selector and then just call: $('#parent').children().filter('.child')
and $('#parent').filter('.child')
respectively.
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.
Based on Anurag's revised speed tests here: 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
On Firefox, Method 3 is still best then method 1/2 and then 4/5
On Opera, Method 3 is still best then method 4/5 and then 1/2
On IE 8, while slower overall than other browsers, it still follows the Method 3, 1,2,4,5 ordering.
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
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屋!