A summary of some common methods of jquery self-band _jquery

Source: Internet
Author: User
Tags getscript shallow copy

itself method ($.each,$.map,$.contains, $ajax)

Common tool Methods

(1) $.trim

The $.trim method removes extra spaces from the head and tail of the string.

Copy Code code as follows:

$.trim (' hello ')/hello

(2) $.contains

The $.contains method returns a Boolean value that indicates whether a DOM element (the second argument) is a subordinate element of another DOM element (the first parameter).

Copy Code code as follows:

$.contains (Document.documentelement, document.body);
True
$.contains (Document.body, document.documentelement);
False

(3) $.each,$.map

The $.each method is used to traverse the array and object, and then return the original object. It accepts two parameters, namely data sets and callback functions.

Copy Code code as follows:

$.each ([+], 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 is important to note that the JQuery object instance also has a each method ($.fn.each), which has a similar effect.

The $.map method is also used to traverse arrays and objects, but returns a new object.

Copy Code code 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 the position of a value in the array (starting from 0). Returns-1 if the value is not in the array.

Copy Code code as follows:

var a = [1,2,3,4];
$.inarray (4,a)//3

(5) $.extend

The $.extend method is used to merge multiple objects into the first object.

Copy Code code 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 that inherits the original object. At this point, its first argument should be an empty object.
Copy Code code 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 object generated by the Extend method is a "shallow copy", that is, if an attribute is an object or an array, only a pointer to the object or array is generated, but the value is not copied. If you want deep copy, you can pass the Boolean value true in the first argument of the Extend method.
Copy Code code 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, the O2 is a shallow copy, and the O3 is a deep copy. As a result, the properties of the original array are changed, and the O2 will change along with the O3.

(6) $.proxy

The $.proxy method is similar to the Bind method for ECMAScript 5, which can bind the context of the function (that is, the This object) and the arguments to return a new function.

The primary use of Jquery.proxy () is to bind a context object for a callback function.

Copy Code code 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 code above, the first callback function has no binding context, so the result is null, there is no output, and the second callback function binds the context to object o, and the result is objects.

Another equivalent of this example is the following:

Copy Code code as follows:

$ ("#button"). On ("Click", $.proxy (o, test))

The $.proxy (o, test) of the above code means that the O method test is bound to O.

This example shows that the method of proxy is mainly written in two ways.

Copy Code code as follows:

Jquery.proxy (function, context)
Or
Jquery.proxy (context, name)

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

Look at one more example. Normally, the This object in the following code points to the DOM object where the click event occurred.

Copy Code code as follows:

$ (' #myElement '). Click (function () {
$ (this). addclass (' Anewclass ');
});

If we want the callback function to run late, using the SetTimeout method, the code will go wrong because settimeout makes the callback function run in the global environment, this points to the global object.
Copy Code code as follows:

$ (' #myElement '). Click (function () {
settimeout (function () {
$ (this). addclass (' Anewclass ');
}, 1000);
});

This in the code above will point to the Global Object window, causing an error.

At this point, you can bind the this object to the MyElement object by using the proxy method.

Copy Code code as follows:

$ (' #myElement '). Click (function () {
settimeout ($.proxy (function () {
$ (this). addclass (' Anewclass ');
}, this), 1000;
});

(7) $.data,$.removedata

The $.data method can be used to store data on a DOM node.

Copy Code code as follows:

Depositing data
$.data (document.body, "foo", 52);
Reading data
$.data (document.body, "foo");
Read all data
$.data (document.body);

The above code stores a key-value pair on the body of the page element, named "foo" with a key value of 52.

The $.removedata method is used to remove the data stored by the $.data method.

Copy Code code as follows:

$.data (Div, "test1", "VALUE-1");
$.removedata (Div, "test1");

(8) $.parsehtml,$.parsejson,$.parsexml

The $.parsehtml method is used to parse a string into a DOM object.

The $.parsejson method is used to parse a JSON string into a JavaScript object, similar to the native Json.parse (). However, jquery does not provide a method similar to Json.stringify (), which does not provide a way to convert a JavaScript object into a JSON object.

The $.parsexml method is used to parse a string into an XML object.

Copy Code code 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

The $.makearray method converts an array-like object into a true array.

Copy Code code as follows:

var a = $.makearray (document.getElementsByTagName ("div"));
(a) $.merge

The $.merge method is used to merge an array (the second argument) into another array (the first argument).
Copy Code code as follows:

var a1 = [0,1,2];
var a2 = [2,3,4];
$.merge (A1, a2);
A1
[0, 1, 2, 2, 3, 4]
(one) $.now

The $.now method returns the number of milliseconds corresponding to the current time from January 1, 1970 00:00:00 UTC, equivalent to (new Date). GetTime ().
Copy Code code as follows:

$.now ()
1388212221489

Ways to determine data types

jquery provides a series of tool methods to determine the data type to compensate for the lack of JavaScript native typeof operators. The following methods determine the parameters and return a Boolean value.

Jquery.isarray (): is an array.
Jquery.isemptyobject (): Is an empty object (does not contain enumerable properties).
Jquery.isfunction (): is a function.
Jquery.isnumeric (): is an array.
Jquery.isplainobject (): Is an object that is generated with "{}" or "new object" instead of the browser-native-provided object.
Jquery.iswindow (): Is a Window object.
Jquery.isxmldoc (): Determines whether a DOM node is in an XML document.
Here are some examples.

Copy Code code as follows:

$.isemptyobject ({})/True
$.isplainobject (document.location)//False
$.iswindow (window)//True
$.isxmldoc (Document.body)//False

In addition to these methods above, there is also a $.type method that returns the data type of a variable. The essence of it is to read the [[Class]] attribute inside the object using the Object.prototype.toString method (see the object section of the standard library).
Copy Code code as follows:

$.type (/test/)//"RegExp"

Ajax operations

$.ajax

The jquery object also defines an Ajax method ($.ajax ()) to handle AJAX operations. When this method is invoked, the browser sends an HTTP request to the server.

$.ajax () is used in a variety of ways, and the most common is to provide an object parameter.

Copy Code code 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) {
$ ('

}
function Errorcallback (XHR, status) {
Console.log (' The problem! ');
}
function Completecallback (XHR, status) {
Console.log (' Ajax request has ended. ');
}


The object arguments for the above code have multiple attributes, meaning the following:

Async: This defaults to true, and if set to False, it indicates that a synchronization request was issued.
Cache: This defaults to true, and if set to False, the browser does not cache data returned by the server. Note that the browser itself does not cache the data returned by the POST request, so it is only valid for head and get requests, even if set to false.
URL: server-side URL. This is the only required property, and other attributes can be omitted.
Type: The HTTP verb used to send information to the server, the default is get, and the other verbs have post, put, DELETE.
DataType: The data type requested to the server can be set to text, HTML, script, JSON, JSONP, and XML.
Data: A message sent to the server, and if the Get method is used, the item is converted to a query string appended to the end of the URL.
Success: The callback function when the request succeeds, the function parameter is the data that the server returns, the status information, the original object that makes the request.
Timeout: The maximum number of milliseconds to wait. If the request has not returned after this time, the request status is automatically changed to fail.
Error: The callback function when the request fails, the function argument is the original object that made the request, and the status information returned.
Complete: A callback function that executes regardless of whether the request succeeds or fails, the function argument is the original object that made the request, and the status information returned.
Among these parameters, the URL can be independent, as the first parameter of the Ajax method. In other words, the code above can also be written as follows.

Copy Code code as follows:

$.ajax ('/url/to/json ', {
Type: ' Get ',
DataType: ' JSON ',
Success:successcallback,
Error:errorcallback
})

Simple wording

Ajax methods also have some simple wording.

$.get (): Makes a GET request.
$.getscript (): Reads a JavaScript script file and executes it.
$.getjson (): Makes a GET request to read a JSON file.
$.post (): Post request issued.
$.fn.load (): reads an HTML file and puts it in the current element.
Generally speaking, these simple methods accept three parameters in turn: URL, data, callback function when successful.

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

These two methods correspond to the HTTP GET method and post method respectively.

Copy Code code 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, namely the server-side URL and the callback function after the request succeeds. The Post method also has a parameter in between the two parameters that represents the data sent to the server.

The above post method corresponds to the AJAX notation as follows.

Copy Code code as follows:

$.ajax ({
Type: ' POST ',
URL: '/data/save ',
Data: {name: ' Rebecca '},
DataType: ' JSON ',
Success:function (RESP) {
Console.log (Json.parse (resp));
}
});

(2) $.getjson ()

Another simple way of writing an Ajax method is the Getjson method. This method can be used instead of the $.ajax method when the server side returns data in JSON format.

Copy Code code as follows:

$.getjson (' Url/to/json ', {' A ': 1}, function (data) {
Console.log (data);
});

The code above is equivalent to the following notation.
Copy Code code as follows:

$.ajax ({
DataType: "JSON",
URL: '/url/to/data ',
Data: {' A ': 1},
Success:function (data) {
Console.log (data);
}
});

(3) $.getscript ()

The $.getscript method is used to load a script file from the server side.

Copy Code code as follows:

$.getscript ('/static/js/myscript.js ', function () {
Functionfrommyscript ();
});

The code above loads the Myscript.js script from the server, and then executes the function provided by the script in the callback function.

The Getscript callback function accepts three parameters, namely the contents of the script file, the status information of the HTTP response, and the Ajax object instance.

Copy Code code as follows:

$.getscript ("Ajax/test.js", function (data, textstatus, JQXHR) {
Console.log (data); The content of Test.js
Console.log (Textstatus); Success
Console.log (Jqxhr.status); 200
});

Getscript is a simple way of writing Ajax methods, so it returns a deferred object that can use the deferred interface.
Copy Code code as follows:

Jquery.getscript ("/path/to/myscript.js")
. Done (function () {
// ...
})
. Fail (function () {
// ...
});

(4) $.fn.load ()

$.fn.load is not a tool approach to jquery, but rather a method defined on the jquery object instance to get the server-side HTML file and place it into the current element. Because this method also belongs to Ajax operations, so put it together here.

Copy Code code as follows:

$ (' #newContent '). Load ('/foo.html ');

The $.fn.load method can also specify a selector that matches the part of the selector in the remote file into the current element and specifies the callback function when the operation completes.
Copy Code code as follows:

$ (' #newContent '). Load ('/foo.html #myDiv h1:first ',
function (HTML) {
Console.log (' Content update! ');
});

The code above loads only the part of the foo.html that matches "#myDiv H1:first", and the specified callback function is run when the load completes.

Ajax Events

jquery provides some of the following methods for specifying callback functions for specific AJAX events.

. Ajaxcomplete (): Ajax request complete.
. Ajaxerror (): Error in AJAX request.
. Ajaxsend (): Before AJAX requests are issued.
. Ajaxstart (): The first Ajax request started out, that is, no AJAX request has yet been completed.
. Ajaxstop (): After all AJAX requests have been completed.
. Ajaxsuccess (): After the successful AJAX request.
The following is an example.

Copy Code code as follows:

$ (' #loading_indicator ')
. Ajaxstart (function () {$ (this). Show ();})
. Ajaxstop (function () {$ (this). Hide ();});

return value

The Ajax method returns a deferred object that you can use to specify a callback function for the object (see the Deferred object section in more detail) then method.

Copy Code code as follows:

$.ajax ({
URL: '/data/people.json ',
DataType: ' JSON '
}). Then (function (RESP) {
Console.log (resp.people);
})

JSONP

The Ajax method can only issue HTTP requests to the domain name of the current Web page because of the "same domain limit" in the browser. However, by inserting a SCRIPT element (\<script>) into the current Web page, you can issue a GET request to a different domain name, which is called JSONP (JSON with Padding).

An Ajax method can emit a JSONP request by specifying datatype as JSONP in an object parameter.

Copy Code code as follows:

$.ajax ({
URL: '/data/search.jsonp ',
Data: {q: ' A '},
DataType: ' Jsonp ',
Success:function (RESP) {
$ (' #target '). html (' Results: ' + resp.results.length);
}
});)

The usual practice for JSONP is to add the name of the callback function after the URL that you want to request. The Ajax method provides that if the requested URL is similar to "callback=?" form, the Jsonp form is automatically used. So the code above can also be written as follows.
Copy Code code as follows:

$.getjson ('/data/search.jsonp?q=a&callback=? '),
function (RESP) {
$ (' #target '). html (' Results: ' + resp.results.length);
}
);

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.