Recently, I have done some small experiments on the use of jQuery selectors to illustrate which of jQuery's different selectors is more efficient and worth using in different situations.
First introduce the jquery file provided by Google and the small plug-in firejspt for testing into the head of each test page.
1. The most commonly used id selector and class selector
Copy the following code 200 times and place it in the body tag.
Compare id Selector and class selector
Compare id selector and class selector
for this time The JS code for the test is as follows:
function ilianTest01(){
$('#ilian').click(function() { alert('Hello World'); });
}
function ilianTest02(){
$('.ilian ').click(function() { alert('Hello World'); });
}
/*Call 2 functions for testing*/
$(function(){
jspt.test(function(){ ilianTest01(); });
jspt.test(function(){ ilianTest02(); });
});
The test results are as follows:
As can be seen from the figure, the efficiency advantage of the id selector compared to the class selector is huge. . . . .
2. When selecting tags, hierarchical selectors are also used very frequently. This comparison test directly sub-tag symbols ">" and children.
Put the following code into the body tag and copy the li tag 500 times.
- Compare the direct child tag symbol ">" with children
- Compare the direct child tag symbol ">" with children
Direct subtag symbols ">" and children
is used this time The JS code for the test is as follows:
function ilianTest01(){
$('#ilian > li').click(function() { alert('Hello World'); });
}
function ilianTest02(){
$( '#ilian').children('li').click(function() { alert('Hello World'); });
}
/*Call 2 functions for testing*/
$(function(){
jspt.test(function(){ ilianTest01(); });
jspt.test(function(){ ilianTest02(); });
}) ;
Test results:
It can be seen that the children selector is better than the direct child tag symbol selector.
Limited to the length of the article, this article only shows the most basic tests, and the above tests were all tested in a simple environment. The test results do not represent an absolute conclusion.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn