JQuery comes with some common methods summary

  • 2020-03-30 03:52:50
  • OfStack

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

Common tool methods

(1) $. Trim

The $.trim method is used to remove excess whitespace from the head and tail of a string.


$.trim('   Hello   ') // Hello

(2) $. The contains

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


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

(3) $.each, $.map

The $.each method is used to iterate over groups and objects, and then return the original object. It takes two arguments, a data set and a callback function.


$.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 is important to note that jQuery object instances also have an each method ($.fn.each), which works in much the same way.

The $.map method is also used to iterate over groups and objects, but returns a new object.


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 at 0). If the value is not in the array, -1 is returned.


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

(5) $. The extend

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


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 from. At this point, its first argument should be an empty object.

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 "shallow copy," which means that if a property is an object or an array, a pointer to that object or array is generated, not a copy of the value. If you want a "deep copy," you can pass in the Boolean value true on the first argument of the extend method.

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 you change the properties of the original array, o2 will change with it, while o3 will not.

(6) $. The proxy

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

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


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 has no context, so the result is null and there is no output. The second callback binds the context to object o, and the result is object.

Another equivalent of this example is:


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

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

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


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

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

Let's do another example. Normally, this object in the following code points to the DOM object where the click event occurs.


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

If we want to delay the callback function, using the setTimeout method, the code will fail because setTimeout makes the callback function run in the global environment, and this will point to the global object.

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

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

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


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

(7) $.data, $.removedata

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


//Save 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 called "foo" on the body of the page element, with a key value of 52.

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


$.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 () method. However, jQuery does not provide a method like json.stringify (), which does not provide a way to convert JavaScript objects into JSON objects.

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


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 real array.


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

The $.merge method is used to merge an array (the second argument) into another array (the first argument).

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 from the current time to 00:00:00 UTC on January 1, 1970, equivalent to (new Date).gettime ().

$.now()
// 1388212221489

Methods for determining data types

JQuery provides a set of tools for determining the typeof data to compensate for JavaScript's native typeof operator. The following method determines the parameter and returns a Boolean value.

JQuery. IsArray () : whether or not it is an array.
Jquery.isemptyobject () : whether it is an empty object (with no enumerable properties).
JQuery. IsFunction () : is it a function?
JQuery. IsNumeric () : whether or not it is an array.
JQuery. IsPlainObject () : whether it is an Object that is generated using "{}" or "new Object" instead of an Object that is native to 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.


$.isEmptyObject({}) // true
$.isPlainObject(document.location) // false
$.isWindow(window) // true
$.isXMLDoc(document.body) // false

In addition to the methods above, there is a $.type method that returns the data type of a variable. It is the essence of the Object. The prototype. The toString method reads Object within [[Class]] attribute (see the Object section of the journal standard library).

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

Ajax operation

$. Ajax

The jQuery object also has an Ajax method ($.ajax()) defined above to handle Ajax operations. When this method is invoked, the browser makes an HTTP request to the server.

$.ajax() can be used in many ways, most commonly by providing an object parameter.


$.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's wrong! ');
}
function completeCallback(xhr, status){
    console.log('Ajax The request has ended. ');
}

The object parameter of the above code has multiple properties, meaning as follows:

Async: this item defaults to true. If set to false, the synchronous request is made.
Cache: this item defaults to true. If 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 set to false, it is only valid for HEAD and GET requests.
Url: server-side address. This is the only required attribute, and all other attributes can be omitted.
Type: the HTTP verb used to send information to the server. The default is GET. The other verbs are POST, PUT, and DELETE.
DataType: the dataType requested from the server, which can be set to text, HTML, script, json, jsonp, and XML.
Data: data sent to the server. If you use the GET method, this is converted to a query string and is attached to the end of the url.
Success: the callback function that takes the data returned by the server, the status information, and the original object that made the request.
Timeout: the maximum number of milliseconds to wait. If the request does not return after this time, the request status is automatically changed to failure.
Error: the callback function when the request fails. The function parameters are the original object that made the request and the state information returned.
Complete: a callback function that executes whether the request succeeds or fails, taking the original object that made the request and the state information returned.
Of these parameters, the url can be isolated as the first parameter of the ajax method. That is, the code above can also be written like this.


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

Simple writing

There are other easy ways to write an ajax method.

$.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() : makes a post request.
$.fn.load() : reads an HTML file and puts it into the current element.
In general, these simple methods take three arguments in turn: the url, the data, and the successful callback function.

(1) $. Get (), $. Post ()

These two methods correspond to HTTP's GET and POST methods, respectively.


$.get('/data/people.html', function(html){
  $('#target').html(html);
});
$.post('/data/save', {name: 'Rebecca'}, function (resp){
  console.log(JSON.parse(resp));
});

The get method takes two arguments, the server-side url and the callback function after the request succeeds. The post method has another parameter in between, which represents the data sent to the server.

The ajax equivalent of the post method above is written as follows.


$.ajax({
    type: 'POST',
    url: '/data/save',
    data: {name: 'Rebecca'},
    dataType: 'json',
    success: function (resp){
      console.log(JSON.parse(resp));
    }
});

(2) $. GetJSON ()

Another easy way to write an ajax method is the getJSON method. When the server side returns data in JSON format, you can use this method instead of the $.ajax method.


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

The code above is the same as the code below.

$.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.


$.getScript('/static/js/myScript.js', function() {
    functionFromMyScript();
});

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

GetScript's callback function takes three arguments, the contents of the script file, the status information of the HTTP response, and the ajax object instance.


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

GetScript is an easy way to write ajax methods, so it returns a deferred object that you can use with the deferred interface.

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

(4) $. Fn. The load ()

$.fn.load is not a jQuery utility method, but a method defined on a jQuery object instance to take the server-side HTML file and put it into the current element. Since this method is also an ajax operation, it's included here.


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

The $.fn.load method can also specify a selector that matches the selector in the remote file into the current element and specifies the callback function when the operation completes.

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

The above code loads only the part of foo.html that matches "#myDiv h1:first" and runs the specified callback function when the load is complete.

Ajax events

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

.ajaxcomplete () : ajax request complete.
.ajaxerror () : ajax request error.
.ajaxsend () : before the ajax request is sent.
.ajaxstart () : the first ajax request is made, that is, no ajax request is completed.
.ajaxstop () : after all ajax requests are completed.
.ajaxsuccess () : after the ajax request succeeds.
Here is an example.


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

The return value

The ajax method returns a deferred object for which you can specify a callback function using the then method (see the deferred objects section for more details).


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

The json

Because of the browser's "co-domain limitation," the ajax method can only make HTTP requests to the domain name of the current web page. However, by inserting script elements into the current page. Script>) , you can make GET requests to different domains, a workaround called JSONP (JSON with Padding).

An ajax method can issue a JSONP request by specifying the dataType as JSONP in the object parameter.


$.ajax({
  url: '/data/search.jsonp',
  data: {q: 'a'},
  dataType: 'jsonp',
  success: function(resp) {
    $('#target').html('Results: ' + resp.results.length);
  }
});)

JSONP typically appends the name of the callback function to the URL to be requested. The ajax approach states that if the url is requested in a form like "callback=?" , the JSONP form is automatically adopted. So, the code above can also be written like this.

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


Related articles: