css选择器对jquery遍历 [英] css selectors vs jquery traversal

查看:232
本文介绍了css选择器对jquery遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery,似乎有两种方法在DOM内的无序列表中查找列表项。

With jquery there seem to be two ways of finding a list item within an unordered list within the DOM.

$("ul>li");

$("ul").find("li"); 

有理由为什么后者更可取?看起来像需要更多的代码才能得到相同的结果。

Is there a reason why the latter might be more preferable? It seems like one would need more code to get the same result.

推荐答案

Yup。速度。 .find()每次都会赢。而处理速度相当!

Yup. Speed. .find() will win every time. And speed of processing is tantamount!

jsPerf速度测试显示我的意思

虽然 .find()会获得一切从属,孩子的孩子,孩子的孩子的孩子等),并且> 是直接孩子选择器。它比以下更好的苹果对苹果:

Although .find() will get everything that is a subordinate (children, children of children, children of children of children, etc), and > is a direct child selector. Its a better apples-to-apples to compare either of the following:


  • $('ul li') vs $('ul')。find('li')

  • $('ul> li') vs $('ul')。children('li')

  • $('ul li') vs $('ul').find('li')
  • $('ul > li') vs $('ul').children('li')

虽然如果你 .find('li'),它仍然是最快的方法它会比 .children('li')

Although if you do .find('li') it'll still be the fastest way to do it, even faster than .children('li').

更新jsPerf以包含 .children()

这篇关于css选择器对jquery遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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