这个问题与绩效有关.
如果我使用如下选择器
$('#myID a') // Does this find #myID and filter by a?
Run Code Online (Sandbox Code Playgroud)
或者我应该写这样的声明?
$('#myID').find('a')
Run Code Online (Sandbox Code Playgroud)
我不确定jQuery是否足够智能以首先使用ID执行此语句,或者它是否像CSS一样操作并从右向左读取.使用标签并不是一件大事,但是当你运行类似的东西时
$('#myID .myClass')
Run Code Online (Sandbox Code Playgroud)
它在性能上有很大的不同.
来自NetTuts文章:http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-think-right-to-left-with-jquery/
作为一个例子,如果Sizzle遇到像$('#box p')这样的选择器,它确实从右到左工作,但是还有一个快速的正则表达式优化,它将首先确定选择器的第一部分是否是一个身份证.如果是这样,它将在搜索段落标记时将其用作上下文.
来自SizzleJS的相关评论:
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
Run Code Online (Sandbox Code Playgroud)