JQuery provides a summary of some common methods.

Source: Internet
Author: User
Tags getscript

JQuery provides a summary of some common methods.

Method ($. each, $. map, $. contains, $ ajax)

Common tools and methods

(1) $. trim

The $. trim method is used to remove unnecessary spaces from the string header and tail.
Copy codeThe Code is as follows:
$. Trim ('hello') // Hello

(2) $. contains

$. Contains returns a Boolean value indicating whether a DOM element (the second parameter) is a lower-level element of another DOM element (the first parameter.
Copy codeThe Code is as follows:
$.Contains(document.doc umentElement, document. body );
// True
$. Contains (document. body, document.doc umentElement );
// False

(3) $. each, $. map

$. Each is used to traverse arrays and objects, and then return the original object. It accepts two parameters: DataSet and callback functions.
Copy codeThe Code is as follows:
$. Each ([52, 97], function (index, value ){
Console. log (index + ":" + value );
});
// 0: 52
// 1: 97
Var obj = {
P1: "hello ",
P2: "world"
};
$. Each (obj, function (key, value ){
Console. log (key + ":" + value );
});
// P1: hello
// P2: world

It should be noted that the jQuery object instance also has an each method ($. fn. each), which has similar functions.

$. Map is also used to traverse arrays and objects, but a new object is returned.
Copy codeThe Code is as follows:
Var a = ["a", "B", "c", "d", "e"];
A = $. map (a, function (n, I ){
Return (n. toUpperCase () + I );
});
// ["A0", "B1", "C2", "D3", "E4"]

(4) $. inArray

$. The inArray method returns a position in the array (starting from 0 ). If the value is not in the array,-1 is returned.
Copy codeThe Code is as follows:
Var a = [1, 2, 4];
$. InArray (4, a) // 3

(5) $. extend

$. Extend is used to merge multiple objects into the first object.
Copy codeThe Code is as follows:
Var o1 = {p1: 'A', p2: 'B '};
Var o2 = {p1: 'C '};
$. Extend (o1, o2 );
O1.p1 // "c"

$. Another use of extend is to generate a new object to inherit the original object. In this case, its first parameter should be an empty object.
Copy codeThe Code is as follows:
Var o1 = {p1: 'A', p2: 'B '};
Var o2 = {p1: 'C '};
Var o = $. extend ({}, o1, o2 );
O
// Object {p1: "c", p2: "B "}

By default, the extend method generates a "shortest copy" object. That is, if an attribute is an object or an array, only a pointer pointing to this object or an array is generated, instead of copying values. If you want to "Deep copy", you can input a Boolean value true in the first parameter of the extend method.
Copy codeThe Code is as follows:
Var o1 = {p1: ['A', 'B']};
Var o2 = $. extend ({}, o1 );
Var o3 = $. extend (true, {}, o1 );
O1.p1 [0] = 'C ';
O2.p1 // ["c", "B"]
O3.p1 // ["a", "B"]

In the code above, o2 is a light copy, while o3 is a deep copy. As a result, the properties of the original array are changed. o2 will change together, but o3 will not.

(6) $. proxy

The $. proxy method is similar to the bind method of ECMAScript 5. It can bind the context (this object) and parameters of the function and return a new function.

JQuery. proxy () is mainly used to bind context objects to callback functions.
Copy codeThe Code is as follows:
Var o = {
Type: "object ",
Test: function (event ){
Console. log (this. type );
}
};
$ ("# Button ")
. On ("click", o. test) // No output
. On ("click", $. proxy (o. test, o) // object

In the above Code, the first callback function is not bound to the context, so the result is null and no output is displayed. The second callback function binds the context to the object o and the result is the object.

Another equivalent method of this example is:
Copy codeThe Code is as follows:
$ ("# Button"). on ("click", $. proxy (o, test ))

The $. proxy (o, test) in the above Code means to bind the test method of o to o.

This example shows that there are two ways to write the proxy method.
Copy codeThe Code is as follows:
JQuery. proxy (function, context)
// Or
JQuery. proxy (context, name)

The first method is to specify the context object for the function, and the second method is to specify the context object and its method name ).

Let's look at another example. Under normal circumstances, the this object in the following code points to the DOM object where the click event occurs.
Copy codeThe Code is as follows:
$ ('# MyElement'). click (function (){
$ (This). addClass ('anewclass ');
});

If we want to delay the running of the callback function, use the setTimeout method to cause an error in the Code. Because setTimeout enables the callback function to run in the global environment, this will point to the global object.
Copy codeThe Code is as follows:
$ ('# MyElement'). click (function (){
SetTimeout (function (){
$ (This). addClass ('anewclass ');
},1000 );
});

In the above Code, this will point to the Global Object window, resulting in an error.

In this case, you can use the proxy method to bind this object to the myElement object.
Copy codeThe Code is as follows:
$ ('# MyElement'). click (function (){
SetTimeout ($. proxy (function (){
$ (This). addClass ('anewclass ');
}, This), 1000 );
});

(7) $. data, $. removeData

$. Data can be used to store data on DOM nodes.
Copy codeThe Code is as follows:
// Store data
$. Data (document. body, "foo", 52 );
// Read data
$. Data (document. body, "foo ");
// Read all data
$. Data (document. body );

The code above stores a key-value pair on the webpage element body, with the key name "foo" and the key value 52.

$. The removeData method is used to remove the data stored by the $. data method.
Copy codeThe Code is as follows:
$. Data (div, "test1", "VALUE-1 ");
$. RemoveData (div, "test1 ");

(8) $. parseHTML, $. parseJSON, $. parseXML

$. ParseHTML is used to parse a string into a DOM object.

$. ParseJSON is used to parse a JSON string into a JavaScript object, which is similar to the native JSON. parse () method. However, jQuery does not provide a method similar to JSON. stringify (), that is, it does not provide a method to convert JavaScript objects into JSON objects.

$. ParseXML is used to parse a string into an XML object.
Copy codeThe Code is as follows:
Var html = $. parseHTML ("hello, <B> my name is </B> jQuery .");
Var obj = $. parseJSON ('{"name": "John "}');
Var xml = "<rss version = '2. 0'> <channel> <title> RSS Title </title> </channel> </rss> ";
Var xmlDoc = $. parseXML (xml );

(9) $. makeArray

$. MakeArray method converts an object similar to an array into a real array.
Copy codeThe Code is as follows:
Var a = $. makeArray (document. getElementsByTagName ("div "));
(10) $. merge

The $. merge method is used to merge an array (the second parameter) into another array (the first parameter.
Copy codeThe Code is as follows:
Var a1 = [0, 1, 2];
Var a2 = [2, 3, 4];
$. Merge (a1, a2 );
A1
// [0, 1, 2, 2, 3, 4]
(11) $. now

The $. now method returns the number of milliseconds corresponding to the current time from 00:00:00 UTC, January 1, January 1, 1970, equivalent to (new Date). getTime ().
Copy codeThe Code is as follows:
$. Now ()
// 1388212221489

How to determine the Data Type

JQuery provides a series of tool methods to determine the data type, to make up for the shortcomings of the JavaScript native typeof operator. The following method is used to determine the parameters and return a Boolean value.

JQuery. isArray (): whether it is an array.
JQuery. isEmptyObject (): whether the object is null (excluding enumerative attributes ).
JQuery. isFunction (): whether it is a function.
JQuery. isNumeric (): whether it is an array.
JQuery. isPlainObject (): whether to generate an Object using "{}" or "new Object" instead of an Object provided by the browser.
JQuery. isWindow (): indicates whether the window object is used.
JQuery. isXMLDoc (): determines whether a DOM node is in an XML document.
The following are some examples.
Copy codeThe Code is as follows:
$. IsEmptyObject ({}) // true
$. IsPlainObject (document. location) // false
$. IsWindow (window) // true
$. IsXMLDoc (document. body) // false

In addition to the above methods, there is also a $. type method that can return the Data type of a variable. It uses the Object. prototype. toString method to read the [[Class] attribute inside the Object (see the Object section in the standard library ).
Copy codeThe Code is as follows:
$. Type (/test/) // "regexp"

Ajax operations

$. Ajax

The jQuery object also defines the Ajax method ($. ajax () to process Ajax operations. After this method is called, the browser sends an HTTP request to the server.

$. Ajax () is used in a variety of ways. The most common is to provide an object parameter.
Copy codeThe Code is as follows:
$. Ajax ({
Async: true,
Url: '/url/to/json ',
Type: 'get ',
Data: {id: 123 },
DataType: 'json ',
Timeout: 30000,
Success: successCallback,
Error: errorCallback,
Complete: completeCallback
})
Function successCallback (json ){
$ ('<H1/>'). text (json. title). appendTo ('body ');
}
Function errorCallback (xhr, status ){
Console. log ('Something went wrong! ');
}
Function completeCallback (xhr, status ){
Console. log ('ajax request has ended. ');
}

The object parameters in the code above have multiple attributes, which are described as follows:

Async: The default value is true. If it is set to false, a synchronous request is sent.
Cache: The default value is true. If it is set to false, the browser does not cache the data returned by the server. Note that the browser itself does not cache the data returned by the POST request, so even if it is set to false, it is only valid for HEAD and GET requests.
Url: the server url. This is the only required attribute. Other attributes can be omitted.
Type: the HTTP verb used to send information to the server. The default value is GET. Other verbs include POST, PUT, and DELETE.
DataType: Data Type requested from the server. It can be set to text, html, script, json, jsonp, and xml.
Data: the data sent to the server. If you use the GET method, this item is converted to a query string and is appended to the end of the URL.
Success: the callback function when the request is successful. The function parameters are the data, status information, and original objects that are returned by the server.
Timeout: the maximum number of milliseconds to wait. If the request has not been returned after this time, the Request status will be changed to fail automatically.
Error: the callback function when the request fails. The function parameter is the original object that sends the request and the returned status information.
Complete: the callback function is executed no matter whether the request is successful or failed. The function parameter is the original object sending the request and the returned status information.
Among these parameters, URLs can be independent and serve as the first parameter of the ajax method. That is to say, the above Code can also be written as follows.
Copy codeThe Code is as follows:
$. Ajax ('/url/to/json ',{
Type: 'get ',
DataType: 'json ',
Success: successCallback,
Error: errorCallback
})

Ease of writing

The ajax method is also easy to write.

$. Get (): sends a GET request.
$. GetScript (): read and execute a JavaScript script file.
$. GetJSON (): sends a GET request to read a JSON file.
$. Post (): sends a POST request.
$. Fn. load (): read an html file and put it into the current element.
In general, these simple methods accept three parameters in sequence: url, data, and callback function when successful.

(1) $. get (), $. post ()

These two methods correspond to the http get method and POST method respectively.
Copy codeThe Code is as follows:
$. Get ('/data/people.html', function (html ){
('{Target'{.html (html );
});
$. Post ('/data/save', {name: 'Rebecca'}, function (resp ){
Console. log (JSON. parse (resp ));
});

The get method accepts two parameters: the server URL and the callback function after the request is successful. The post method has a parameter between the two parameters, indicating the data sent to the server.

The ajax method corresponding to the post method is as follows.
Copy codeThe Code is as follows:
$. Ajax ({
Type: 'post ',
Url: '/data/save ',
Data: {name: 'Rebecca '},
DataType: 'json ',
Success: function (resp ){
Console. log (JSON. parse (resp ));
}
});

(2) $. getJSON ()

Another convenient method for ajax is the getJSON method. When the server returns data in JSON format, you can use this method instead of the $. ajax method.
Copy codeThe Code is as follows:
$. GetJSON ('url/to/json', {'A': 1}, function (data ){
Console. log (data );
});

The above code is equivalent to the following code.
Copy codeThe Code is as follows:
$. Ajax ({
DataType: "json ",
Url: '/url/to/data ',
Data: {'A': 1 },
Success: function (data ){
Console. log (data );
}
});

(3) $. getScript ()

$. GetScript is used to load a script file from the server.
Copy codeThe Code is as follows:
$. GetScript ('/static/js/myScript. js', function (){
FunctionFromMyScript ();
});

The above code first loads the myScript. js script from the server, and then runs the function provided by the script in the callback function.

The callback function of getScript accepts three parameters: the content of the script file, the HTTP response status information, and the ajax object instance.
Copy codeThe Code is as follows:
$. GetScript ("ajax/test. js", function (data, textStatus, jqxhr ){
Console. log (data); // content of test. js
Console. log (textStatus); // Success
Console. log (jqxhr. status); // 200
});

GetScript is a simple method for writing ajax methods. Therefore, a deferred object is returned, and the deferred interface can be used.
Copy codeThe Code is as follows:
JQuery. getScript ("/path/to/myscript. js ")
. Done (function (){
//...
})
. Fail (function (){
//...
});

(4) $. fn. load ()

$. Fn. load is not a jQuery tool method, but a method defined on the jQuery object instance. It is used to obtain the HTML file on the server and put it into the current element. This method is also an ajax operation, so let's talk about it here.
Copy codeThe Code is as follows:
$ ('# Newcontent'). load ('/foo.html ');

The $. fn. load method can also specify a selector to put the part matching the selector in the remote file into the current element and specify the callback function when the operation is complete.
Copy codeThe Code is as follows:
$ ('# Newcontent'). load ('/foo.html # myDiv h1: first ',
Function (html ){
Console. log ('content update! ');
});

The callback Code only matches the section "# myDiv h1: first" in foo.html. After loading, the specified callback function is run.

Ajax events

JQuery provides the following methods to specify callback functions for specific AJAX events.

. AjaxComplete (): the ajax request is complete.
. AjaxError (): ajax request error.
. AjaxSend (): Before the ajax request is sent.
. AjaxStart (): The first ajax request is sent, that is, no ajax request has been completed.
. AjaxStop (): After all ajax requests are completed.
. AjaxSuccess (): After the ajax request is successful.
The following is an example.
Copy codeThe Code is as follows:
$ ('# Loading_indicator ')
. AjaxStart (function () {$ (this). show ();})
. AjaxStop (function () {$ (this). hide ();});

Return Value

The ajax method returns a deferred object. You can use the then method to specify a callback function for this object (for details, see the deferred object section ).
Copy codeThe Code is as follows:
$. Ajax ({
Url: '/data/people. json ',
DataType: 'json'
}). Then (function (resp ){
Console. log (resp. people );
})

JSONP

Because the browser has "same domain restrictions", the ajax method can only send HTTP requests to the domain name of the current webpage. However, by inserting a script element (\ <script>) into the current webpage, you can send a GET request to different domain names. This method is called JSONP (JSON with Padding ).

The ajax method can send a JSONP request by specifying the ype as JSONP in the object parameters.
Copy codeThe Code is as follows:
$. Ajax ({
Url: '/data/search. jsonp ',
Data: {q: 'A '},
DataType: 'jsonp ',
Success: function (resp ){
Certificate ('{target'}.html ('results': '+ resp. Results. length );
}
});)
The common practice of JSONP is to add the name of the callback function after the URL to be requested. The ajax method specifies that if the requested URL is similar to "callback = ?" Is automatically in the JSONP format. Therefore, the above Code can also be written as follows.
Copy codeThe Code is as follows:
$. GetJSON ('/data/search. jsonp? Q = a & callback =? ',
Function (resp ){
Certificate ('{target'}.html ('results': '+ resp. Results. length );
}
);


Jquery technical materials

Of course, it is an official document. In fact, you read the content of api.jquery.com and read it. There is no problem with understanding jQuery.
On the Chinese Sina love question sharing page, there is a jquerybasics tutorial. (jonathanchaffer&karlswedberg?. .pdf, which is not convenient to post a link here. You can search for it directly.

The common js in Html is jQuery ??

Javascript is short for javascript.
The history of javascript is almost the same as that of the Internet. With the advent of the netscape browser, javascript was born.

Jquery is a library or framework of javascript, which greatly simplifies the development of dynamic web pages. Jquery 1.0 was released in 2006. The latest version is 1.4.2 and is still very young.

Related Article

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.