$('#tabs a')和$('#tabs')之间的区别.find('a')

Ans*_*rta 38 javascript jquery pycharm

我有以下结构

<ul id="tabs" class="nav nav-tabs">
    <li><a href="#aaa" hashval="aaa">AAA</a></li>
    <li><a href="#bbb" hashval="bbb">BBB</a></li>
    <li><a href="#ccc" hashval="ccc">CCC</a></li>
    <li><a href="#ddd" hashval="ddd">DDD</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

现在我通过以下代码操作锚标记,并且工作正常.

$('#tabs a[href="#ddd"]').tab('show');
Run Code Online (Sandbox Code Playgroud)

我正在使用pycharm,它通过说"带ID选择器的前言"为该行添加警告.单击它时,pycharm将更改为以下内容

$('#tabs').find('a[href="#ddd"]').tab('show');
Run Code Online (Sandbox Code Playgroud)

两者都工作正常,但我不明白其中的区别.

是什么在两个或更具体的区别是什么区别$('#tabs a[href="#ddd"]')$('#tabs').find('a[href="#ddd"]')

Mat*_*nya 52

$("#tabs a") evaluates from right to left - which is the native direction of both Sizzle selector engine and querySelectorAll - i.e. first it finds all of the anchor elements in the page and then narrows it down to those under #tabs.

$("#tabs").find("a") evaluates - more intuitively - from left to right, i.e. first it finds #tabs, and then only the anchor elements under it.

Clearly the latter would yield better performance, but it would only be noticeable accumulatively; that is, if you run thousands of queries. Otherwise, the difference is negligible.

  • +1,值得注意的是,第一个将使用本机`querySelectorAll`(如果可用),如果没有,则返回jQuery引擎. (6认同)
  • **两个**都使用Sizzle;) (3认同)

Roh*_*mar 7

"从左到右增加特异性"中所述:

对jQuery的选择器引擎有一点了解很有用.它首先从最后一个选择器开始工作,因此在旧版浏览器中,查询如下:

$("p#intro em");
Run Code Online (Sandbox Code Playgroud)

将每个em元素加载到一个数组中.然后它会处理每个节点的父节点并拒绝那些无法找到p#intro的节点.如果页面上有数百个em标记,则查询效率会特别低.

根据您的文档,可以通过首先检索最佳限定选择器来优化查询.然后它可以用作子选择器的起点,例如

$("em", $("p#intro")); // or
$("p#intro").find("em");
Run Code Online (Sandbox Code Playgroud)

测试用例$("#tabs > a")最快的


Eri*_*ric 5

The second one is MUCH quicker. The reason being jQuery's selector enginge Sizzle, which traverses the selection from right to left, not vice versa.

This means that the selector

$('#tabs a[href="#ddd"]')
Run Code Online (Sandbox Code Playgroud)

First queries the DOM document for a tag, which contains the attribute href set to #ddd. It then filteres out all of them, to get every one that is a <a> tag. At last, it traverses up the DOM tree for every node, trying to find a parent #tabs.

Imagine a site with 1.000 tags with href="#ddd", how tremendously slow that would be.

THEN.

The other variation pycharm suggest, is to first locate a element #tabs. This is super-quick, since jQuery can utilize the native browser method getElementById(). Having this node, it can traverse down to find all tags that are matching. By doing this, not all tags in the whole DOM-tree, needs to be checked. Only those which actually are in #tabs.

有关详细信息,请查看文档中的此页面.