This article mainly introduces 14 useful Jquery skills. This article provides some performance optimization skills, encoding optimization skills, and concise methods. For more information, see.
1. return the Jquery object instance through a method
Use var someDiv = $ ('# somediv'). hide (); instead of var someDiv = $ (' # somediv'); someDiv. hide ();
2. use find to find
Use $ ('# somediv '). find ('P. someClass '). hide (); replace $ ('# someDiv p. someClass '). hide (); because it does not need to trigger the Sizzle engine of Jquery, and tries to make your selection operator simple while optimizing the rightmost selection operator when writing the selector.
3. do not abuse $ (this)
Use $ ('# someAnchor '). click (function () {alert (this. id) ;}); replace $ ('# someAnchor '). click (function () {alert ($ (this ). attr ('id '));});
4. short form of ready
Use $ (function () {}); instead of $ (document). ready (function (){});
5. secure your code
Method 1 (using noConflict)
The code is as follows:
Var j = jQuery. noConflict ();
J ('# somediv'). hide ();
// The line below will reference some other library's $ function.
$ ('Somediv'). style. display = 'none ';
Method 2 (input parameter Jquery)
The code is as follows:
(Function ($ ){
// Within this function, $ will always refer to jQuery
}) (JQuery );
Method 3 (using the ready method)
The code is as follows:
JQuery (document). ready (function ($ ){
// $ Refers to jQuery
});
6. simplified code
Replace for with each, save temporary variables using arrays, and use document fragment. this is the same as writing native Javascript.
7. Ajax method
Jquery provides useful ajax methods such as get getJSON post ajax.
8. access native attributes and methods
For example, the methods to obtain element IDs include:
The code is as follows:
// OPTION 1-Use jQuery
Var id = $ ('# someAnchor'). attr ('id ');
// OPTION 2-Access the DOM element
Var id = $ ('# someAnchor') [0]. id;
// OPTION 3-Use jQuery's get method
Var id = $ ('# someAnchor'). get (0). id;
// OPTION 3b-Don't pass an index to get
AnchorsArray = $ ('. someAnchors'). get ();
Var thirdId = anchorsArray [2]. id;
9. use PHP to check Ajax requests
By using xhr. setRequestHeader ("X-Requested-With", "XMLHttpRequest"), the server can use
The code is as follows:
Function isXhr (){
Return $ _ SERVER ['http _ X_REQUESTED_WITH '] === 'xmlhttprequest ';
}
To check whether it is an Ajax request. it may be used when Javascript is disabled.
10. relationship between Jquery and $
At the bottom of the Jquery code, you can see the following code
Window. jQuery = window. $ = jQuery; $ is actually a closed cut of Jquery.
11. conditional loading of Jquery
The code is as follows: