Home  >  Article  >  Web Front-end  >  Summary of some common methods that come with jQuery_jquery

Summary of some common methods that come with jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:37:341077browse

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

Common tools and methods

(1)$.trim

The $.trim method is used to remove excess spaces at the beginning and end of the string.

Copy code The code is as follows:

$.trim(' Hello ') // Hello

(2)$.contains

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

Copy code The code is as follows:

$.contains(document.documentElement, document.body);
// true
$.contains(document.body, document.documentElement);
// false

(3) $.each, $.map

The $.each method is used to iterate through arrays and objects, and then return the original object. It accepts two parameters, which are the data collection and the callback function.

Copy code The 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 jQuery object instances also have an each method ($.fn.each), and the two have similar functions.

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

Copy code The 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 the position of a value in the array (starting from 0). If the value is not in the array, -1 is returned.

Copy code The code is as follows:

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

(5)$.extend

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

Copy code The 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. At this time, its first parameter should be an empty object.
Copy code The 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 object generated by the extend method is a "shallow copy", that is, if a property is an object or array, only a pointer to the object or array will be generated, and the value will not be copied. If you want a "deep copy", you can pass the Boolean value true in the first parameter of the extend method.
Copy code The 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 above code, o2 is a shallow copy and o3 is a deep copy. As a result, if the properties of the original array are changed, o2 will change along with it, but o3 will not.

(6)$.proxy

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

The main use of jQuery.proxy() is to bind context objects to callback functions.

Copy code The 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 does not bind the context, so the result is empty and there is no output; the second callback function binds the context to the object o, and the result is object.

Another equivalent way of writing this example is:

Copy code The code is as follows:

$("#button").on( "click", $.proxy(o, test))

The $.proxy(o, test) in the above code means to bind o's method test to o.

This example shows that there are two main ways to write the proxy method.

Copy code The code is as follows:

jQuery.proxy(function, context)
// or
jQuery.proxy(context, name)

The first way of writing is to specify the context object (context) for the function (function), and the second way of writing is to specify the context object (context) and one of its method names (name).

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 code The code is as follows:

$('#myElement').click(function() {
$(this).addClass('aNewClass');
});

If we want the callback function to run delayed and use the setTimeout method, the code will go wrong, because setTimeout causes the callback function to run in the global environment, and this will point to the global object.
Copy code The code is as follows:

$('#myElement').click(function() {
setTimeout(function() {
          $(this).addClass('aNewClass');
}, 1000);
});

This in the above code will point to the global object window, causing an error.

At this time, you can use the proxy method to bind this object to the myElement object.

Copy code The code is as follows:

$('#myElement').click(function() {
setTimeout($.proxy(function() {
          $(this).addClass('aNewClass');
}, this), 1000);
});

(7)$.data, $.removeData

$.data method can be used to store data on DOM nodes.

Copy code The code is as follows:

//Save data
$.data(document.body, "foo", 52 );
//Read data
$.data(document.body, "foo");
// Read all data
$.data(document.body);

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

The $.removeData method is used to remove the data stored in the $.data method.

Copy code The code is as follows:

$.data(div, "test1", "VALUE-1");
$.removeData(div, "test1");

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

The $.parseHTML method is used to parse strings into DOM objects.

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(), that is, it does not provide a method to convert JavaScript objects into JSON objects.

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

Copy code The code is as follows:

var html = $.parseHTML("hello, my name is jQuery.");
var obj = $.parseJSON('{"name": "John"}');
var xml = "RSS Title";
var xmlDoc = $.parseXML(xml);

(9)$.makeArray

The $.makeArray method converts an array-like object into a real array.

Copy code The code is as follows:

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

The $.merge method is used to merge one array (second parameter) into another array (first parameter).
Copy code The 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 on January 1, 1970, which is equivalent to (new Date).getTime().
Copy code The code is as follows:

$.now()
// 1388212221489

Methods to determine data type

jQuery provides a series of tool methods for determining data types to make up for the shortcomings of JavaScript's native typeof operator. The following method judges the parameters and returns a Boolean value.

jQuery.isArray(): Whether it is an array.
jQuery.isEmptyObject(): Whether it is an empty object (does not contain enumerable properties).
jQuery.isFunction(): Whether it is a function.
jQuery.isNumeric(): Whether it is an array.
jQuery.isPlainObject(): Whether it is an object generated using "{}" or "new Object" instead of an object provided natively by the browser.
jQuery.isWindow(): Whether it is a window object.
jQuery.isXMLDoc(): Determines whether a DOM node is in an XML document.
Here are some examples.

Copy code The 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. Its essence is to use the Object.prototype.toString method to read the [[Class]] attribute inside the object (see the Object section of the "Standard Library").
Copy code The code is as follows:

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

Ajax operation

$.ajax

The jQuery object also defines an Ajax method ($.ajax()) to handle Ajax operations. After calling this method, the browser will send an HTTP request to the server.

$.ajax() can be used in many ways, the most common is to provide an object parameter.

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

').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 of the above code have multiple attributes, the meanings are as follows:

async: This item defaults to true. If set to false, it means that a synchronous request is issued.
cache: This item defaults to true. If set to false, the browser will not cache the data returned by the server. Note that the browser itself will not cache the data returned by the POST request, so even if it is set to false, it will only be effective for HEAD and GET requests.
url: server-side URL. This is the only required attribute, other attributes can be omitted.
type: HTTP verb used to send information to the server. The default is GET. Other verbs include POST, PUT, and DELETE.
dataType: The data type requested from the server, which can be set to text, html, script, json, jsonp and xml.
data: Data sent to the server. If the GET method is used, this item will be converted into a query string and appended to the end of the URL.
success: callback function when the request is successful. The function parameters are the data returned by the server, status information, and the original object that issued the request.
timeout: The maximum number of milliseconds to wait. If the request has not returned after this time, the request status will be automatically changed to failed.
error: callback function when the request fails. The function parameters are the original object that issued the request and the returned status information.
complete: A callback function that will be executed regardless of whether the request succeeds or fails. The function parameters are the original object that issued the request and the returned status information.
Among these parameters, url can be independent and used as the first parameter of the ajax method. In other words, the above code can also be written as follows.

Copy code The code is as follows:

$.ajax('/url/to/json',{
Type: 'GET',
dataType: 'json',
success: successCallback,
error: errorCallback
})

Simple writing method

There are also some simple ways to write the ajax method.

$.get(): Make a GET request.
$.getScript(): Read a JavaScript script file and execute it.
$.getJSON(): Issue a GET request to read a JSON file.
$.post(): Make a POST request.
$.fn.load(): Read an html file and put it into the current element.
Generally speaking, these convenience methods accept three parameters in order: url, data, and callback function on success.

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

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

Copy code The 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, which are the server-side URL and the callback function after the request is successful. The post method has another parameter between these two parameters, which represents the data sent to the server.

The ajax writing method corresponding to the above post method is as follows.

Copy code The 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 simple way to write the ajax method is the getJSON method. When the server returns data in JSON format, this method can be used instead of the $.ajax method.

Copy code The code is as follows:

$.getJSON('url/to/json', {'a': 1}, function(data){
console.log(data);
});

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

$.ajax({
dataType: "json",
url: '/url/to/data',
data: {'a': 1},
Success: function(data){
console.log(data);
}
});

(3)$.getScript()

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

Copy code The 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 executes the function provided by the script in the callback function.

The callback function of getScript accepts three parameters, which are the content of the script file, the status information of the HTTP response and the ajax object instance.

Copy code The code is as follows:

$.getScript( "ajax/test.js", function (data, textStatus, jqxhr){
console.log( data ); // Contents of test.js
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
});

getScript is a simple way of writing the ajax method, so it returns a deferred object and you can use the deferred interface.
Copy code The code is as follows:

jQuery.getScript("/path/to/myscript.js")
.done(function() {
               // ...
})
.fail(function() {
               // ...
});

(4)$.fn.load()

$.fn.load is not a tool method of jQuery, but a method defined on the jQuery object instance, which is used to obtain the server-side HTML file and put it into the current element. Since this method also belongs to ajax operation, it will be discussed here together.

Copy code The code is as follows:

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

The $.fn.load method can also specify a selector, put the part of the remote file that matches the selector into the current element, and specify a callback function when the operation is completed.
Copy code The code is as follows:

$('#newContent').load('/foo.html #myDiv h1:first',
Function(html) {
console.log('Content updated!');
});

The above code only loads the part of foo.html that matches "#myDiv h1:first". After the loading is completed, the specified callback function will be run.

Ajax event

jQuery provides the following methods for specifying callback functions for specific AJAX events.

.ajaxComplete(): The ajax request is completed.
.ajaxError(): Ajax request error.
.ajaxSend(): before the ajax request is issued.
.ajaxStart(): The first ajax request starts to be issued, that is, there is no ajax request yet to be completed.
.ajaxStop(): After all ajax requests are completed.
.ajaxSuccess(): After the ajax request is successful.
Below are examples.

Copy code The code is as follows:

$('#loading_indicator')
.ajaxStart(function (){$(this).show();})
.ajaxStop(function (){$(this).hide();});

Return value

The ajax method returns a deferred object, and you can use the then method to specify a callback function for the object (see the "Deferred Object" section for detailed explanation).

Copy code The code is as follows:

$.ajax({
url: '/data/people.json',
dataType: 'json'
}).then(function (resp){
console.log(resp.people);
})

JSONP

Due to the "same domain restriction" in the browser, the ajax method can only make HTTP requests to the domain name of the current web page. However, by inserting a script element (