Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

javascript - Difference between $('#tabs a') and $('#tabs').find('a')

I have following structure

<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>

Now I am operating on the anchor tag by following code and which is working fine.

$('#tabs a[href="#ddd"]').tab('show');

I am using pycharm which adds warning for the line by saying "Preface with ID selector". When I click it, pycharm changes to following

$('#tabs').find('a[href="#ddd"]').tab('show');

Both are working fine but I don't understand the difference.

What is the difference in both or more specifically what is difference between $('#tabs a[href="#ddd"]') and $('#tabs').find('a[href="#ddd"]')?

question from:https://stackoverflow.com/questions/17569766/difference-between-tabs-a-and-tabs-finda

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$("#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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...