jQuery 中最快的 children() 或 find() 是什么? [英] What is fastest children() or find() in jQuery?

查看:24
本文介绍了jQuery 中最快的 children() 或 find() 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在 jQuery 中选择一个子节点,可以使用 children() 也可以使用 find().

To select a child node in jQuery one can use children() but also find().

例如:

$(this).children('.foo');

给出相同的结果:

$(this).find('.foo');

现在,哪个选项是最快或首选的,为什么?

Now, which option is fastest or preferred and why?

推荐答案

children() 只查看节点的直接子节点,而 find() 遍历节点下方的整个 DOM,因此 children() 应该 给定等效实现更快.但是,find() 使用 native 浏览器方法,而 children() 使用在浏览器中解释的 JavaScript.在我的实验中,典型情况下的性能差异不大.

children() only looks at the immediate children of the node, while find() traverses the entire DOM below the node, so children() should be faster given equivalent implementations. However, find() uses native browser methods, while children() uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.

使用哪个取决于您是只想考虑DOM中的直接后代还是此节点下的所有节点,即根据您想要的结果选择合适的方法,而不是方法的速度.如果性能确实是一个问题,那么请尝试找到最佳解决方案并使用它(或查看此处其他答案中的一些基准).

Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).

这篇关于jQuery 中最快的 children() 或 find() 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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