Summary of some common methods that come with jQuery_jquery
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.
$.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).
$.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.
$.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.
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.
var a = [1,2,3,4];
$.inArray(4,a) // 3
(5)$.extend
$.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 the original object. At this time, its first parameter 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 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.
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.
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:
$("#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.
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.
$('#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.
$('#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.
$('#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.
//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.
$.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.
var html = $.parseHTML("hello, my name is jQuery.");
var obj = $.parseJSON('{"name": "John"}');
var xml = "
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 one array (second parameter) into another array (first parameter).
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().
$.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.
$.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").
$.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.
$.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.
$.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.
$.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.
$.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.
$.getJSON('url/to/json', {'a': 1}, function(data){
console.log(data);
});
The above code is equivalent to the following writing.
$.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.
$.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.
$.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.
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.
$('#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.
$('#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.
$('#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).
$.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 (<script>) into the current web page, you can make GET requests to different domain names. This workaround is called JSONP (JSON with Padding). </script>
The ajax method can issue a JSONP request by specifying 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);
}
});)
The usual approach to JSONP is to add the name of the callback function after the URL to be requested. The ajax method stipulates that if the requested URL ends in a form similar to "callback=?", it will automatically be in JSONP format. Therefore, the above code can also be written as follows.
$.getJSON('/data/search.jsonp?q=a&callback=?',
function(resp) {
$('#target').html('Results: ' resp.results.length);
}
);

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools