jquery Usage Tips Simple Summary _jquery

Source: Internet
Author: User
Tags ming tag name
1. Use the latest jquery version
Think this proposal is open to question, although the new jquery version of the performance is better, but some of the changes will lead to a number of bugs, such as from 1.4.2 to 1.5 when many friends complained that there is a problem with Ajax. The suggestion is that the jquery upgrade of the old page should be cautious and the new project can be boldly used in the new jquery version.

Another suggestion is to use the jquery file on Google's CDN to load more quickly. Bash Google libraries API into view.
Copy Code code as follows:

<!--Include A specific version of JQuery-->
<script src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<!--Include The latest version in the 1.6 branch-->
<script src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" ></script>

2. Maintain the simplicity of the selector
This suggestion Ming River very much agree, have a lot of friends do not like to add style or ID to element, want to keep HTML concise, use jquery powerful selector to retrieve element, this is not good habit. First, the more complicated the selector, the lower the efficiency of traversal, it is obvious that the highest efficiency is undoubtedly the use of native getElementById (); second, complex selectors solidify the tag name and hierarchy, if your HTML structure changes, or if the label changes, are directly responsible for the retrieval failure.
Copy Code code as follows:

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

Accessing the DOM is the most resource-and performance-consuming part of JavaScript, so try to avoid complex or repetitive traversal of the DOM.
The way to avoid repeating the DOM is to store the elements retrieved by $ () to a variable, such as the following code:
Copy Code code as follows:

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

Using the $ prefix to mark jquery objects is a very good habit, recommended.
Copy Code code as follows:

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

The jquery selector supports most of the CSS3 pseudo class methods, such as: visible,: Hidden, animated, although very convenient, but please use caution, because when you use the Pseudo class selector, jquery has to use Queryselectorall (), The loss of performance is even greater.

The 3.jQuery object is treated as an array
The jquery object defines the length property, and returns a DOM element instead of a child jquery object, such as the following code, when using the form of an array.
Copy Code code as follows:

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

Traversing buttons Objects
Copy Code code as follows:

for (Var i=0;i<buttons.length;i++) {
Console.log (Buttons[i]); is a DOM element, not a jquery Object!
}

We can even slice it:
Copy Code code as follows:

var firstfour = Buttons.slice (0,4);

Depending on the experiment, the execution efficiency is higher than the $.each () using a for or while loop. Detailed testing can be seen several times faster.
Use the Length property to check the presence of elements:
Copy Code code as follows:

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

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

4.selector Properties
The jquery object comes with a selector property that gets the selector name, such as:
Copy Code code as follows:

$ (' #container li:first-child '). Selector//#container Li:first-child
$ (' #container Li '). Filter (': First-child '). Selector//#container Li.filter (: First-child)

Notice the second line of code, selector returns the complete selector of the element that was fetched.
This property is often used when writing jquery plug-ins.

5. Create an empty jquery object
This scenario is not much used when you need to create an empty jquery object first and then use the Add () method to inject the jquery object into this object.
Copy Code code as follows:

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

6. Select random Elements
There are not many applications, for example, now you need to randomly add a red class to li.
You need to extend the jquery selector, which is a good example of how jquery.expr is used.
Copy Code code 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.
One.}) (JQuery);
12.
13.
14.
15.$ (' Li:random '). addclass (' Glow ');

7. Use CSS hooks
Jquery.csshooks is the 1.4.3 new method, not much used, and when you define a new CSS hooks you actually define the getter and setter methods, for instance, Border-radius This fillet property wants to be successfully applied to browsers such as Firefox, WebKit and so on, adding attribute prefixes such as-moz-border-radius and-webkit-border-radius. You can define CSS hooks to encapsulate it as a unified interface Borderradius instead of one by one to set CSS properties.
Copy Code code 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:
12.$ (' #rect '). CSS (' Borderradius ', 5);

8. Use a custom easing (ease animation effect) function
Easing plugin is a very large number of functions, can achieve a lot of gorgeous results. You can also customize the easing function when the built-in easing effect doesn't meet your needs.
Copy Code code 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 ');

use of 9.$.proxy ()
About $.proxy (), Minghe has introduced in detail, the portal in this "jquery1.4 Tutorial III: New Methods Tutorial (3)."
jquery has a headache where there are too many callback functions, the context this is always changing, and sometimes we need to control the point of this, and then we need the $.proxy () method.
Copy Code code as follows:

<div id= "Panel" style= "Display:none" >
<button>Close</button>
</div>
$ (' #panel '). FadeIn (function () {
This is points to #panel
$ (' #panel button '). Click (function () {
This is points to the button
$ (this). Fadeout ();
});
10.});

Nested two callback functions this point is different! Now we want this to point to a #panel element. The code is as follows:
Copy Code code as follows:

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

$ (' #panel button '). Click ($.proxy (function () {
This is points to #panel
$ (this). Fadeout ();
},this));
});

10. Get the number of nodes quickly
This is a common technique with the following code:
Copy Code code as follows:

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

11. Build a jquery plugin
Copy Code code as follows:

(function ($) {
$.fn.yourpluginname = function () {
Your Code goes here
return this;
};
}) (JQuery);

On the construction of jquery Plug-ins, Minghe has sent a series of tutorials, Portal: The production of jquery text hint Plug-ins-jquery plug-in hands-on tutorial (1).
There is no more detail here.

12. Set AJAX global Events
About AJAX global events, Minghe has sent a complete introductory article, Portal: "jquery Ajax global Event detailed-Minghe talk about jquery."

13. Delay Animation
Copy Code code as follows:

This is wrong:
$ (' #elem '). Animate ({width:200},function () {
settimeout (function () {
$ (' #elem '). Animate ({margintop:100});
},2000);
});

Do it as this:
$ (' #elem '). Animate ({width:200}). Delay. Animate ({margintop:100});

When there are multiple animate animations, how to handle the order of the animation is a worry, the original author is recommended to use the delay () function, such as the above code, but the Ming River's proposal is to use the queue () method, because delay you have to consider how much time delay, and queue does not Functions that enter the queue are executed sequentially. Can see the Ming River before the article queue and dequeue-Minghe talk about jquery.

15.jquery of local storage
Local storage is increasingly used in Web applications today, and jquery has a plugin dedicated to local storage called $.jstorage jquery plugin.
Copy Code code 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);
}

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.