Recently, I have made some small experiments on jQuery selector usage to demonstrate Which of the following is more efficient and worth using different jQuery selectors under different circumstances.
First, introduce the jquery file provided by google and the small plug-in firejspt for testing in the head of each test page.Copy codeThe Code is as follows: <! -- Introduce the library file of FireJSPT -->
<Script type = "text/javascript" src = "firejspt. js"> </script>
<! -- Introduce jQuery library files of version 1.44 provided by google. In fact, it doesn't matter which version it is. -->
<Script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> </script>
1. The most common id selector and class selector
Copy the following code 200 times and place it in the body tag.Copy codeThe Code is as follows: <div id = "ilian"> comparison id selector and class selector </div>
<Div class = "ilian"> comparison id selector and class selector </div>
The JS Code used for this test is as follows:Copy codeThe Code is as follows: function ilianTest01 (){
$ ('# Ilian'). click (function () {alert ('Hello World ');});
}
Function ilianTest02 (){
$ ('. Ilian'). click (function () {alert ('Hello World ');});
}
/* Call two functions for testing */
$ (Function (){
Jspt. test (function () {ilianTest01 ();});
Jspt. test (function () {ilianTest02 ();});
});
The test results are as follows:
The efficiency advantage of id selector compared with class selector is very good .....
2. the hierarchical selector is frequently used when selecting tags. In this comparison test, the sub-label symbols ">" and children are used directly.
Put the following code into the body tag and copy the li tag 500 times.Copy codeThe Code is as follows: <ul id = "ilian">
<Li> compare the direct sub-label symbols ">" and children </li>
<Li> compare the direct sub-label symbols ">" and children </li>
<Li> compare the direct sub-label symbols ">" and children </li>
<! -- Omitted 497 times -->
</Ul>
The JS Code used for this test is as follows:Copy codeThe Code is as follows: function ilianTest01 (){
$ ('# Ilian> li'). click (function () {alert ('Hello World ');});
}
Function ilianTest02 (){
$ ('# Ilian'). children ('lil'). click (function () {alert ('Hello World ');});
}
/* Call two functions for testing */
$ (Function (){
Jspt. test (function () {ilianTest01 ();});
Jspt. test (function () {ilianTest02 ();});
});
Test results:
The children selector is better than the direct sub-tag symbol selector.
Limited by the length of the article, this article only shows the most basic tests, and the above tests are all tested in a simple environment, the test results do not represent an absolute conclusion.