Home > Web Front-end > JS Tutorial > body text

A simple summary of jQuery usage tips_jquery

WBOY
Release: 2016-05-16 17:36:11
Original
1143 people have browsed it
1. Use the latest jquery version
I think this suggestion is debatable. Although the newer jquery version has better performance, some changes in methods will still cause some bugs, such as from 1.4.2 to In 1.5, many friends complained about problems with ajax. The suggestion is that you should be careful when upgrading jquery for old pages, and you can boldly use the new version of jquery for new projects.

Another suggestion is to use jquery files on Google’s CDN, which will load faster. Click on the Google Libraries API to view it.
Copy code The code is as follows:




2. Keep the selector simple
Minghe agrees very much with this suggestion. There are many friends who don’t like to add styles or ids to elements and hope to keep it HTML is simple and it is not a good habit to use jquery's powerful selector to retrieve elements. First of all, the more complex the selector, the lower the traversal efficiency. This is obvious. The highest efficiency is undoubtedly to use the native getElementById(); secondly, the complex selector solidifies the tag name and hierarchical structure in it. If your html structure Changes or label changes will directly cause retrieval failure.
Copy code The code is as follows:

$('li[data-selected="true" ] a') // Fancy, but slow
$('li.selected a') // Better
$('#elem') // Best

Access DOM, It is the most resource- and performance-consuming part of JavaScript, so try to avoid complex or repeated traversal of the DOM.
The way to avoid repeatedly traversing the DOM is to store the elements retrieved by $() into variables, such as the following code:
Copy code The code is as follows:

var buttons = $('#navigation a.button');

// It is very good to use the $ prefix to mark jquery objects habits, recommended to use.
Copy code The code is as follows:

var $buttons = $('#navigation a.button ');
var $buttons = $('#navigation a.button');

jquery selector supports most of the css3 pseudo-class methods, like :visible, :hidden, : animated, although very convenient, please use it with caution, because when you use pseudo-class selectors, jQuery has to use querySelectorAll(), which incurs greater performance losses.

3. The jQuery object is processed as an array
The jQuery object defines the length attribute. When operated in the form of an array, the returned DOM element is actually a DOM element rather than a child jQuery object, such as the following code .
Copy code The code is as follows:

// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');

// Traverse button objects
Copy code The code is as follows:

for(var i=0;iconsole.log(buttons[i]); // It is a DOM element, Instead of jQuery objects!
}

// We can even slice it:
Copy code The code is as follows:

var firstFour = buttons.slice(0,4);

According to experiments, using a for or while loop has higher execution efficiency than $.each() . For detailed tests, see several times faster.
Use the length attribute to check element existence:
Copy code The code is as follows:

if(buttons){ // This is always true
// Do something
}

if(buttons.length){ // True only if buttons contain elements
// Do something
}

4.selector attribute
jQuery objects all have a selector attribute, which is used to get the selector name, such as:
Copy Code The code is as follows:

$('#container li:first-child').selector // #container li:first-child
$( '#container li').filter(':first-child').selector // #container li.filter(:first-child)

Pay attention to the second line of code, selector returns Gets the complete selector of the element.
This attribute is often used when writing jquery plug-ins.

5. Create an empty jQuery object
There are not many application scenarios in this case. When you need to create an empty jQuery object first, then use the add() method to add it to it. It is used when injecting jQuery objects into objects.
Copy code The code is as follows:

var container = $([]);
container.add(another_element);)

6. Select a random element
There are not many application scenarios. For example, now you need to randomly add a red to li class.
You need to extend jquery's selector. This code demonstrates the usage of jQuery.expr very well.
Copy code The code is as follows:

(function($){
var random = 0;

$.expr[':'].random = function(a, i, m, r) {
if (i == 0) {
random = Math.floor( Math.random() * r.length);
}
return i == random;
};
10.
11.})(jQuery);
12.
13.
14.
15.$('li:random').addClass('glow');

7. Use css hooks
jQuery.cssHooks is a new method added in 1.4.3. It is estimated that it is not used much. When you define new CSS Hooks, you actually define the getter and setter methods. For example, the border-radius circle If you want the angular attribute to be successfully applied to browsers such as Firefox and WebKit, you need to add attribute prefixes, such as -moz-border-radius and -webkit-border-radius. You can encapsulate it into a unified interface borderRadius by defining CSS Hooks instead of setting css properties one by one.
Copy code The code is as follows:

$.cssHooks['borderRadius'] = {
get: function(elem, computed, extra){
// Depending on the browser, read the value of
// -moz-border-radius, -webkit-border-radius or border-radius
},
set: function(elem, value){
// Set the appropriate CSS3 property
}
};
10.
11.// Use it without worrying which property the browser actually understands:
12.$('#rect').css('borderRadius',5);

8. Use custom Easing (easing Animation effect) function
The easing plugin is a very commonly used function and can achieve many gorgeous effects. When the built-in easing effect cannot meet your needs, you can also customize the easing function.
Copy code The code is as follows:

$.easing.easeInOutQuad = function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t b;
return -c/2 * ((--t)*( t-2) - 1) b;
};

// To use it:
$('#elem').animate({width:200},'slow',' easeInOutQuad');

9. The use of $.proxy()
About $.proxy(), Minghe once introduced it in detail, the portal is here "jquery1 .4 Tutorial 3: New method tutorial (3)》.
Jquery has a troublesome place. There are too many callback functions, and the context this is always changing. Sometimes we need to control the direction of this, and then the $.proxy() method is needed.
Copy code The code is as follows:


$('#panel').fadeIn(function(){
// this points to #panel
$('#panel button').click(function(){
// this points to the button
$(this).fadeOut();
});
10.});

The this points of the two nested callback functions are different! Now we want this to point to the #panel element. The code is as follows:
Copy the code The code is as follows:

$('#panel').fadeIn(function(){
// Using $.proxy to bind this:

$('#panel button').click( $.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});

10. Get the number of nodes quickly
This is a common technique, the code is as follows:
Copy code The code is as follows:

console.log( $('*').length );

11. Build a jquery plug-in
Copy code The code is as follows:

(function($){
$. fn.yourPluginName = function(){
// Your code goes here
return this;
};
})(jQuery);

About jquery plug-in To build, Minghe once posted a series of tutorials, Portal: Making a jquery text prompt plug-in—jquery plug-in practical tutorial (1).
I won’t go into details here.

12. Set ajax global events
Regarding ajax global events, Minghe once posted a complete introduction article, portal: "Detailed explanation of ajax global events in jquery - Minghe talks about jquery" .

13. Delay animation
Copy code The code is as follows:

// This is wrong:
$('#elem').animate({width:200},function(){
setTimeout(function(){
$('#elem ').animate({marginTop:100});
},2000);
});

// Do it like this:
$('#elem'). animate({width:200}).delay(2000).animate({marginTop:100});

When there are multiple animate animations, how to deal with the execution order of animations is a troublesome thing. The author of the original article suggests using the delay() function, such as the code above, but Minghe’s suggestion is to use the queue() method, because with delay you have to consider how much time to delay, but queue does not have this problem, and the functions that enter the queue will be executed one by one. . You can read Minghe’s previous article queue and dequeue—Minghe talks about jquery.

15. jquery’s local storage
Local storage is used more and more frequently in today’s web applications. jquery has a plug-in specifically for local storage called $.jStorage jQuery plugin .
Copy code The code is as follows:

// Check if "key" exists in the storage
var value = $.jStorage.get("key");
if(!value){
// if not - load the data from the server
value = load_data_from_server();
// and save it
$.jStorage.set("key",value);
}
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template