Simple jQuery skills

Source: Internet
Author: User

1. Use the latest jquery version

I think this suggestion is open to discussion. Although the newer jquery version has better performance, changes in some methods will still lead to some bugs, for example, from 1.4.2 to 1.5, many friends complained about problems with ajax. We recommend that you be cautious when upgrading jquery on the old page. The new version of jquery can be used in new projects.
We also recommend that you use jquery files on google cdn to load files faster. Click Google Libraries API to view details.

2. Keep the selector simple

This suggestion is highly endorsed by minghe. Many friends do not like to add styles or IDs to elements. They hope to keep html concise and use jquery's powerful selector to retrieve elements. This is not a good habit. First, the more complex the selector, the lower the traversal efficiency, which is obvious. The highest efficiency is undoubtedly the use of native getElementById (). Second, complex selectors fix tag names and hierarchies. If your html structure is changed or the tag is changed, retrieval fails.


[Javascript]
$ ('Li [data-selected = "true"] A') // Fancy, but slow
$ ('Li. selected A') // Better
$ ('# Elem') // Best

$ ('Li [data-selected = "true"] A') // Fancy, but slow
$ ('Li. selected A') // Better
$ ('# Elem') // Best

Accessing the DOM is the most costly and performance part of javascript, so try to avoid complex or repeated DOM traversal.
The method to avoid repeated DOM traversal is to store the elements retrieved by $ () to variables, such as the following code:
[Javascript]
Var buttons = $ ('# navigation a. click ');

Var buttons = $ ('# navigation a. click ');

// It is a good habit to use the $ prefix to mark jquery objects.
[Javascript]
Var $ buttons = $ ('# navigation a. click ');

Var $ buttons = $ ('# navigation a. click ');

Jquery selector supports most css3 pseudo-class methods, such as: visible,: hidden,: animated. Although this is very convenient, please use it with caution, because when you use a pseudo-class selector, jQuery has to use querySelectorAll (), which causes more performance loss.


3. jQuery objects are processed as Arrays

The jQuery object defines the length attribute. When an array is used for operations, the returned result is actually a DOM element rather than a subjquery object, such as the following code.


[Javascript] ttons:
Var buttons = $ ('# navigation a. click ');

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


// Traverse the buttons object
[Javascript]
For (var I = 0; I <buttons. length; I ++ ){
Console. log (buttons [I]); // It is a DOM element, not a jQuery object!
}

For (var I = 0; I <buttons. length; I ++ ){
Console. log (buttons [I]); // It is a DOM element, not a jQuery object!
}


// We can even slice it:
[Javascript]
Var firstFour = buttons. slice (0, 4 );

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

According to the experiment, the execution efficiency of the for or while loop is higher than that of $. each. For detailed tests, see several times faster.
Use the length attribute to check the element existence:
[Javascript]
If (buttons) {// This is always true
// Do something
}
 
If (buttons. length) {// True only if buttons contains elements
// Do something
}

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

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

 


4. selector attributes

Each jQuery object has a selector attribute to obtain the selector name. For example:


[Javascript]
$ ('# Container li: first-child'). selector // # container li: first-child
$ ('# Container li'). filter (': first-child'). selector // # container li. filter (: first-child)

$ ('# 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. The selector returns the complete selector of the retrieved element.
This attribute is often used when writing jquery plug-ins.


5. Create an empty jQuery object

In this case, there are not many application scenarios. You need to create an empty jQuery object first, and then use the add () method to inject jQuery objects into this object.


[Javascript]
Var container = $ ([]);
Container. add (another_element );)

Var container = $ ([]);
Container. add (another_element );)

 


6. Select Random Elements

There are not many application scenarios. For example, you need to randomly Add a red class to li.


[Javascript]
 

The jquery selector needs to be extended. This Code demonstrates the usage of jQuery. expr.

[Javascript]
(Function ($ ){
Var random = 0;
 
$. Expr [':']. random = function (a, I, m, r ){
If (I = 0 ){
Random = Math. floor (Math. random () * r. length );
}
Return I = random;
};
 
}) (JQuery );
 
 
 
$ ('Li: random '). addClass ('glow ');

(Function ($ ){
Var random = 0;

$. Expr [':']. random = function (a, I, m, r ){
If (I = 0 ){
Random = Math. floor (Math. random () * r. length );
}
Return I = random;
};

}) (JQuery );

 

$ ('Li: random '). addClass ('glow ');

 


7. Use css hooks

JQuery.css Hooks is a new method added in 1.4.3, which is not estimated to be used much. When you define the new CSS Hooks, The getter and setter methods are actually defined. For example, to apply the border-radius attribute to firefox, webkit, and other browsers, you need to add the attribute prefix, such as-moz-border-radius and-webkit-border-radius. You can encapsulate CSS Hooks into a unified interface borderRadius instead of setting css attributes one by one.


[Javascript]
Developer.css Hooks ['borderradius '] = {
Get: function (elem, computed, extra ){
// Depending on the browser, read the value
//-Moz-border-radius,-webkit-border-radius or border-radius
},
Set: function (elem, value ){
// Set the appropriate CSS3 property
}
};
 
// Use it without worrying which property the browser actually understands:
Certificate ('employee rect').css ('borderradius ', 5 );

Developer.css Hooks ['borderradius '] = {
Get: function (elem, computed, extra ){
// Depending on the browser, read the value
//-Moz-border-radius,-webkit-border-radius or border-radius
},
Set: function (elem, value ){
// Set the appropriate CSS3 property
}
};

// Use it without worrying which property the browser actually understands:
Certificate ('employee rect').css ('borderradius ', 5 );

 


8. Use the custom Easing Function

Easing plugin is a lot of functions that can achieve a lot of gorgeous results. When the built-in easing effect cannot meet your needs, you can also customize the easing function.


[Javascript]
$. Easing. easeInOutQuad = function (x, t, B, c, d ){
If (t/= d/2) <1) return c/2 * t + B;
Return-c/2 * (-- t) * (t-2)-1) + B;
};
 
// To use it:
$ ('# Elem'). animate ({width: 200}, 'low', 'easeinoutquad ');

$. Easing. easeInOutQuad = function (x, t, B, c, d ){
If (t/= d/2) <1) return c/2 * t + B;
Return-c/2 * (-- t) * (t-2)-1) + B;
};

// To use it:
$ ('# Elem'). animate ({width: 200}, 'low', 'easeinoutquad ');

 


9. $. Use of proxy ()

For details about $. proxy (), minghe once described the portal in jquery1.4 tutorial 3: add method tutorial (3).
Jquery has a headache. There are too many callback functions, and the context this is always changing. Sometimes we need to control the point of this. At this time, we need the $. proxy () method.


[Javascript]
<Div id = "panel" style = "display: none">
<Button> Close </button>
</Div>
$ ('# Panel'). fadeIn (function (){
// This points to # panel
$ ('# Panel button'). click (function (){
// This points to the button
$ (This). fadeOut ();
});
});

<Div id = "panel" style = "display: none">
<Button> Close </button>
</Div>
$ ('# Panel'). fadeIn (function (){
// This points to # panel
$ ('# Panel button'). click (function (){
// This points to the button
$ (This). fadeOut ();
});
});

The nested two callback functions this point to different! Now we want this to point to the # panel element. The Code is as follows:
[Javascript
$ ('# Panel'). fadeIn (function (){
// Using $. proxy to bind this:
 
$ ('# Panel button'). click ($. proxy (function (){
// This points to # panel
$ (This). fadeOut ();
}, This ));
});

$ ('# 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:


[Javascript]
Console. log ($ ('*'). length );

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

 


11. Build a jquery plug-in

 

[Javascript]
(Function ($ ){
$. Fn. yourPluginName = function (){
// Your code goes here
Return this;
};
}) (JQuery );

(Function ($ ){
$. Fn. yourPluginName = function (){
// Your code goes here
Return this;
};
}) (JQuery );

For the construction of the jquery plug-in, minghe once issued a series of tutorials, portal: Create the jquery text prompt plug-in-jquery plug-in practical tutorial (1 ).
I will not detail it here.


12. Set ajax global events

For ajax global events, minghe once published a complete introduction Article, "details about jquery's ajax global events-minghe talks about jquery".


13. Delayed Animation

 

[Javascript]
// 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 });

// 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 animations, the sequence of animation execution is troublesome. The original author suggests using the delay () function, as shown in the code above, however, we recommend that you use the queue () method. Because you need to consider the delay, and the queue does not have this problem, the functions that enter the queue will be executed sequentially. You can refer to the previous articles queue and dequeue-minghe about jquery.


15. jquery Local Storage

Local Storage is frequently used in web applications. jquery has a plug-in called $. jStorage jQuery plugin for local storage.


[Javascript]
// 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 );
}

// 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 );
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.