preface

Trend in today’s front frame, there is no doubt that the React, Vue has walked in the first line, more and more front end developers to join them, but the former overlord jQuery still remain, in the past year’s research (original: yq.aliyun.com/articles/71…). JQuery is still at the top of the list, and I am currently maintaining an old project, so I will read sharp jQuery again for more understanding.

advantage

There are too many advantages. Personally, I think the selectors, DOM operation encapsulation, chain operation and so on are really excellent.

The installation

You can use jQuery directly by importing the script tag into the file

JQuery object and DOM object

The jQuery object is a wrapper around the DOM object for use in jQuery. The two are somewhat different things.

Document.getelementbyid (‘my’) is used to find an element on the page whose ID is my.

JQuery object: the DOM object is generated after jQuery wraps the DOM object. Why do we need to wrap the DOM object, because the wrapped DOM object (that is, jQuery object) can use jQuery methods. These methods greatly simplify the JS writing rules, such as:

// In jQuery, the element node with id my has been selected
$('#my')

// in js, this is required to select the element node with id my
document.getELementById('my')
Copy the code

JQuery objects are somewhat different from DOM objects, so the two methods are not interchangeable. For example:

// Get the document contents of the element with id my
$('#my'). The HTML ();// The HTML () method is provided by jQuery.
// Therefore, objects that can use HTML () must be jQuery objects
document.getELementById('my').html()

// Get the same content in a DOM object, such as using methods provided by the DOM
document.getELementById('my').innerHTML
Copy the code

DOM objects are transformed into jQuery objectsTo convert a DOM object into a jQuery object, use the(document. GetELementById (” my “));

JQuery object to DOM object: In jQuery object implementation, we put all the element nodes in a class array, so we can get DOM object by subscript, such as:

$('.my')
// Get all element nodes with my in the class of the page, all element nodes in a class array
$('.my')[0] = $('.my')[0]

Copy the code

The selector

There is no doubt in my mind that the selector feature in jQuery is definitely at the top of the list… There is no way, it is too easy to use, it fully inherits the style of CSS selector, can quickly and easily find special DOM elements, processing, and to encounter errors, avoid browser error and blocking the process;

Basic selector

The selector describe return The sample
#id Matches an element with the specified ID A single element $(‘#my’) to get the element with id my
.class Matches all elements whose class names contain class Set of elements $(‘.test’) to get all elements whose class names contain test
element Matches all elements with the specified element name Set of elements $(‘p’) retrieves all p elements
* Matches all elements on the page Set of elements $(‘*’) to get all the elements on the page
el1,el2,el3 Match all selectors and return them together Set of elements $(‘div,.test,#my’) returns all div elements with test and id my

Hierarchy selector

The selector describe return The sample
$(‘el div’) Matches all div elements within the EL element (including children, grandchildren, and all descendants) Set of elements $(‘#my div’) returns all div elements within the element with id my
$(‘el>div’) Match all div elements in el’s child elements (only child elements, no grandchildren, etc.) Set of elements $(‘#my>div’), get all div elements in the child element with id my
$(‘el+div’) Matches the div element immediately following the EL element Set of elements $(‘p+div’) gets all div elements immediately following the p element
$(‘el~div’) Matches all sibling elements after el Set of elements $(‘p+div’) gets the div elements after all p elements

Filter selector (common only)

The selector describe return The sample
:first Pick the first element A single element $(‘div:first’) selects the first element of all div elements
:last Pick the last element A single element $(‘div:last’) selects the last element of all div elements
:not(el) Removes elements other than the specified element Set of elements $(‘div:not(.test)’) selects all div elements except those whose class name is test
:even All elements whose indexes are even, starting at 0 Set of elements $(‘div:even’), gets all div elements, and selects all divs whose indexes are even
:odd All elements with odd indexes start at 0 Set of elements $(‘div:odd’), gets all div elements, and selects all divs whose indexes are odd
:eq(index) Selects the element whose index is equal to index, starting at 0 A single element $(‘div:eq(10)’), get all div elements, select div whose index is 10
:gt(index) Selects an element whose index is greater than index, starting at 0 Set of elements $(‘div:gt(2)’), get all div elements, and select any div whose index is greater than 2
:lt(index) Selects an element whose index is less than index, starting at 0 Set of elements $(‘div:lt(5)’), get all div elements, and select div elements whose indexes are less than 5
:header Select all header elements, such as H1,h2 Set of elements $(‘:header’), select all h1, H2… , etc.
:animated Selects all elements that are animating Set of elements $(‘div: Anpops ‘), selects all the div elements that are performing the animation
:hidden Selects all invisible elements Set of elements (‘input:hidden’)
:visiable Selects all visible elements Set of elements $(‘div:visible’) selects all visible div elements
[attr] Select the element that has this attribute Set of elements $(‘div[id]’) selects the element with the ID attribute
[attr=value] Select the element whose attribute value is value Set of elements $(‘div[title=test]’) select the element whose title is “test”
[attr!=value] Select the element whose attribute value does not equal value Set of elements $(‘div[title!=test]’);Note: If the element has no title attribute, it will also be selected
[attr^=value] Attribute values start with value Set of elements $(‘div[title^=test]’), the selected element has the title attribute, and the value of the title attribute starts with test
[attr$=value] Attribute values end with value Set of elements $(‘div[title^=test]’), the selected element has the title attribute, and the value of the title attribute ends in test
[attr*=value] The property value contains value Set of elements $(‘div[title^=test]’), the selected element has the title attribute, and the title attribute value contains the string test
[attr1][attr2][attr3] A composite filter combines multiple filters together. The selected elements must meet the requirements at the same time Set of elements $(‘div[id][title^=test]’), the selected div must have an ID attribute, and the title attribute must start with test
:nth-child(index/even/odd/eq) Select the index child or odd or even element under each parent element Set of elements :eq(index) retrives a single element, nth-child matches child elements for each parent element, and nth-child is evaluated from 1, and the index of eq(index) is evaluated from 0 :nth-child(even), Nth-child (odd); nth-child(2n); nth-child(3n); nth-child(3n) Nth-child (3n+1), the element whose index under all parent elements is a multiple of 3
:first-child The first child of each parent element Set of elements $(‘ul li:first-child’), select the first li element under each ul element on the page
:last-child The last child of each parent element Set of elements $(‘ul Li :last-child’), selects the last li element under each ul element on the page
:only-child Is selected if an element is the only child of its parent Set of elements $(‘ul li:only-child’), select the only li element under each UL element on the page, in other words, the li must be the only child element in ul
:enable All available elements Set of elements $(‘#form:enable’), select all available elements in the form
:disabled All elements that are not available Set of elements $(‘#form:disable’), select all elements in the form whose ID is not available
:checked All selected elements must be single and multiple Set of elements $(‘input:checked’) selects all checked input elements
:selected All selected option elements, such as drop-down menus Set of elements $(‘select:selected’) selects all selected elements
:input Select all of the input, textarea,, the select button Set of elements $(‘:input’)
:text Select all single lines of text Set of elements $(‘:text’)
:password Check all the password boxes Set of elements $(‘:password’)
:radio Check all the checkboxes Set of elements $(‘:radio’)
:checkbox Select all the check boxes Set of elements $(‘:checkbox’)
:submit Check all submit buttons Set of elements $(‘:submit’)
:image Select all the image buttons Set of elements $(‘:image’)
:reset Check all reset buttons Set of elements $(‘:reset’)
:button Select all the buttons Set of elements $(‘:button’)
:file Select all upload domains Set of elements $(‘:file’)
:hidden Select all invisible elements Set of elements $(‘:hidden’)

Notes in the selector

Special characters

If the selected attribute value in the selector has special characters, such as #,[], etc., then you need to use escape, otherwise an error will be reported, such as:

$('#id#b')	// This is an error
$('#id\\#b')	// Need # escape

$('#id[1]')	// This is an error
$('#id\\[1\\]')	// Need to escape
Copy the code

Quotation marks problem

$('#id[title="test"]')
Copy the code

Space problem

The space in the selector has a meaning of its own, representing descendants

$('.test :hidden')	// Select the element node hidden in the descendant element of the element with test in the class name

$('.test:hidden')	// All class names with test and hidden elements are selected
Copy the code

DOM manipulation

Manipulating the DOM is a two-step process. The first step is to find the element node to manipulate. Step 2: Modify the element node;

Find element nodes

With the selector above, you can get all the elements you need;

Operations on element nodes

Attributes of the element node

methods describe The sample
.attr() Gets or sets the attributes of an element node Access to:(‘ class ‘). Attr (‘ title ‘, ’10’), will beAll the name of the class$(‘.test’).attr(‘class’,’title’) $(‘.test’).attr(‘class’,’title’) Setting is not an add-on. It does not append title to the value of the class. Instead, it replaces the value of the class as a whole with title.
.removeArrt() Deletes an attribute of an element node $(‘.class’).removeattr (‘title’) removes the title attribute from all elements with class names

Element node operation

methods describe The sample
$(‘<li title=”10″></li>’) Using the $() method, you can create a DOM object by wrapping a pair of HTML tags, and then add element nodes to the specified DOM via the node-addition method Let title= ‘<h1 title=”10″> title </h1>’let(title)The title); Add an H1 title to all elements with class names. In fact, adding strings directly to the DOM also works, such as: let title= ‘<h1 title=”10″> title </h1>’$(‘.class’).append(title);
append() To each matched elementInternal appendThe append content is placed inside the elementThe back $(‘.class’).append(‘<h1 title=”10″>)
appendTo() $(a).append(b) appendTo adds content to a; $(a).append(b) appendTo adds content to B $(‘<h1 title=”10″>).append(‘.class’)
prepend() To each matched elementInternal appendThe append content is placed inside the elementThe front of $(‘.class’).prepend(‘<h1 title=”10″>)
prependTo() $(a).prepend(b) prepend(b) prepend(B) prepend(B); $(a).prepend(b) prepend(B) prepend(B) $(‘<h1 title=”10″>).prepend(‘.class’)
after() To all matchesAfter the elementAdds the specified content, unlike append, etc., to the append locationIt’s not internal, it’s external, it’s sibling $(‘ class ‘.) after (‘ < h1 title = “10” >) / / add the sample after the < div class = ‘class’ > < / div > < h1 title = ’10’ > < / h1 >
insertAfter() $(a).after(b), insertAfter, insertAfter, inserts a after b $(‘<h1 title=”10″>).insertAfter(‘.class’)
before To all matchesBefore the elementAdds the specified content, unlike append, etc., to the append locationIt’s not internal, it’s external, it’s sibling $(‘ class ‘). Before (‘ < h1 title = “10” >) / / add the sample after < h1 title = ’10’ > < / h1 > < div class = ‘class’ > < / div >
.remove() To remove the selected node (including its child elements), this method returns a value that is the element of the node to be removed, and can take arguments in the same way that selectors write, further limiting the range of elements to be removed $(‘.class’).remove() removes all class elements and their children from the class name. Example 1: Let li = (‘ul li:eq(2)’).remove(), let li = (‘ul li:eq(2)’).remove(), Delete all li under UL whose title value is equal to “pineapple”
.empty() Rather than deleting a node, it is clearing the designationInside the nodeAll the children of $(‘ul li’).empty(), empty all child elements of ul li.
.clone() This method takes one argument, which is a Boolean value. When true, it makes a deep copy, including the events bound to it. If no arguments are written, it simply copies the HTML structure (this).clone().appendto (‘#test’)}) add li and its children to element test
replaceWith() Replaces all selected element nodes with the specified content $(” p “). ReplaceWith (< h1 > hello < / h1 > ‘), will replace all p elements < h1 > hello < / h1 >
replaceAll() Replacing elements with all specified content differs from replaceWith() in that,(a).replaceall (B) is exactly the opposite, replacing all a with B $(‘ < h1 > hello < / h1 > ‘). The replaceWith (” p “), will replace all p elements < h1 > hello < / h1 >
.wrap() Wraps all matched elements individually with the specified tag $(‘strong’).wrap(‘<b><b/>’)
.wrapAll() Wrap matched elements together. The difference is that wrap wraps each element separately, while wrapAll wraps all elements together if multiple elements are contiguous $(‘ strong ‘). WrapAll (‘ < b > < / b > ‘) example, after the execution: < b > < strong > 1 < / strong > < strong > 1 < / strong > < / b >
.wrapInner() Wrap all contents inside the matching element together $(‘ strong ‘). WrapInner (‘ < b > < / b > ‘) example: < strong > < b > 1 < / b > < / strong >

Style operation

methods describe The sample
adClass() To the selected jquery objectAdditional styleAdd a new value to the original class value. If multiple values are added, separate them with Spaces, such as addClass(‘test1 test2’). <li class=’title’></li> test$(.title”).addClass(‘test’)
removeClass() RemoveClass (‘test1 test2’) <li class=’title’></li> test$(.title”).addClass(‘test’)
toggleClass() Back and forth stylesIf the specified class name exists on the target element, it is removed; if not, it is added $(.title”).toggleClass(‘test’)
hasClass() judgeIf a class name exists, the return value is a Boolean, true if it does, false if it does not // Check whether.title contains the class name test$(.title “).hasClass(‘test’)

Sets and gets HTML, text, and values

methods describe The sample
html() Similar to the innerHTML method in JS, you can set the HTML content of an element. Note that this method replaces all the content inside the selected element node with the specified content / / set the HTML(‘.test’).html()
text() Sets or gets the text content under the specified element. Unlike HTML (), which gets the content including HTML tags, text() only gets the text content, not the HTML tags / / set(‘.test’).text()
val() Sets or gets the value of an element, such as a drop-down selection, checkbox, input field, or checkbox / / set(‘input’).val()

Traverse the nodes

methods describe The sample
children() Traverses all child nodes under the specified element node. You can set parameters to add qualifiers. Note:It’s just child nodes, excluding the grandchild node and the descendant element node below // Find all child nodes under the element whose class name contains the class name test, and set a title attribute for them with a value of helloThe ‘(‘). The children (‘ div’). Attr (‘ title ‘, ‘hello’)
next() Of the specified elementUnder theOne node, notice that it isElements at the same level $(‘.test’).next().attr(‘title’,’ hello ‘).attr(‘title’,’ hello ‘)
prev() Of the specified elementonOne node, notice that it isElements at the same level $(‘.test’).prev().attr(‘title’,’ hello ‘).attr(‘title’,’ hello ‘)
siblings() Finds all other sibling elements of the specified element node (excluding the selected node) $(‘.test’).siblings().attr(‘title’,’ hello ‘).siblings().attr(‘title’,’ hello ‘)

CSS-DOM

Simply get or set the CSS style of the object

css() You can get or set the style of a given element. If you set a CSS style with a “-“, such as font-size, use the hump style and capitalize the first letter, such as: fontSize let color =(‘.test’).css(‘fontSize’,’18px’),$(‘.test’).css({‘fontSize’:’18px’,’color’:’#888888′})
height() You can get or set the height of the specified element Get let height =(‘.test’).height(100)
width() You can get or set the width of the specified element Get let width =(‘.test’).width(100)
offset() This method has two attributes that get the relative values of the specified elementThe offset of the windowThat’s how far from the top, how far to the left / / on the left side of the(‘.test’).offset().top
position() This method also has two properties that get values relative toThe last position attribute is the left and top distance of the relative or Absolute attribute / / on the left side of the(‘.test’).position().top
scrollTop() The distance from the top of an element’s scroll bar, often used in element contenthighlyWhen the window content is exceeded, the scroll bar appears. Click the button button to scroll to the specified position $(‘.test’).scrollTop(100)

Events and animations in jQuery

Load the DOM

//javascript
window.onload={
	...
}
//jq
  $(document).ready(function(){... })/ / short
  $(function(){... })Copy the code

Window. onload is executed after the document has been loaded, including the image load. If multiple window. onloads are written, the later one overwrites the previous one.

$(function()) is executed when the DOM is loaded, not when all images have been downloaded.

event

on() Two parameters, the first is the event type, and the second is the callback function after the event is fired. Multiple events can be separated by Spaces; The first event type is: Blur, focus, load, resize, Scroll, unload, Click, DBLClick, Mousedown, Mouseup, Mousemove, mouseover, mouseout, mouseEnter, Mouseleave, change, Select, submit, keyDown, keyPress, keyUp, error // Bind the click event, that is, the second function is triggered when the element is clicked(‘.test’).on(‘mouseover mouseout’,function(){})
off() To unbind an object to which an event is bound, you can take an argument, which is the name of the function to which the event is bound. If the function name is not passed, all events bound to the object will be cleared // Unbind all bind events(‘.test’).on(‘click’,fn1=function(){})$(‘.test’).off(‘click’,’fn1′)
one() An event that can only take effect once $(‘.test’). One (‘click’,fn1=function(){})
hover(enter,leave) This is aSynthetic events, simulating the hover event of the mouse, there are two parameters, the wind is different from two methods, the first is the method triggered when the mouse moves in, the second is the method triggered when the mouse moves out $(‘.test’).hover(function(){},function(){})
toggle(fn1,fn2,… funN) This is also a composite event. Each click on the element triggers the functions inside it, such as fn1 when clicked once, fn2 when clicked a second time, fnN when clicked the NTH time, and then starting with fn1 $(‘.test’).toggle(function(){},function(){})
event.stopPropagation() Prevents events from bubbling $(‘.test’).on(‘click’,function(event){event.stopPropagation()})
event.preventDefault() Blocking default events $(‘.test’).on(‘click’,function(event){event.preventDefault(a)})
event.type Gets the current event type $(‘.test’).on(‘click’,function(event){// return clickevent.type;})
event.target Gets the element that is currently firing the event $(‘.test’).on(‘click’,function(event){// Returns the current.test elementevent.target;})
event.pageX The current cursor is in the x coordinate of the page $(‘.test’).on(‘click’,function(event){event.pageX;})
event.pageY The current cursor is in the y coordinate of the page $(‘.test’).on(‘click’,function(event){event.pageY;})
trigger() Simulation event, after opening the page, simulation with a certain operation, of course simulation refers to simulation operation, operation after the execution of the code should be written normally, for example,Simulate a click button, click after the execution of the function to write normallyNote: This method performs browser defaults, such as $(‘input’).trigger(‘focus’); Input executes the focus event and gets the focus $(‘.test’).trigger(‘click’)
triggerHandler() Execute events, howeverDefault actions are not triggered. For example, the input focus event above executes the focus event, but does not get the focus $(‘input’).triggerHandler(‘focus’)

The namespace

You can add namespaces for events so that you only need to delete the specified namespace when deleting events

// Plugin is the namespace
$('.test').on('click.plugin'.function(event){})

Click on the second namespace of the event on.test
$('.test').on('click.aaa'.function(event){})

//.test has no namespace for click events
$('.test').on('click'.function(event){})
Copy the code

So, to delete one of the above click events, just need to

// Only the.aaa click event will be deleted. Unnamed and variously named events will not be deleted
$('.test').off('.aaa')
Copy the code

Therefore, the simulation of click events needs to trigger the specified namespace click events

// the exclamation mark after click! , is to match the click method that is not included in the namespace
$('.test').trigger('click! ')

// If you need to match all clicks, normal emulation will do
$('.test').trigger('click')
Copy the code

animation

show() Change the display value of the object to block,There are two parameters, the first can be a specified keyword,slow, normal, fast, or a specific millisecond. The second is the callback function, which is executed when show() is fully executed $(‘.test’).show(1500,function(){})
hide() Change the display of the object to None,There are two parameters, the first can be the specified keyword,slow, normal, fast, or the specific millisecond. The second is the callback function, which is executed when the hide() function is fully executed $(‘.test’).hide(1500,function(){})
fadeIn() Gradually change the opacity of the object to full display,There are two parameters, the first can be the specified keyword,slow, normal, fast, or the specific millisecond. The second is the callback function, which is executed when the fadeIn() function is fully executed $(‘.test’).fadeIn(1500,function(){})
fadeOut() Gradually change the opacity of the object to completely hidden,There are two parameters, the first can be the specified keyword,slow, normal, fast, or the specific millisecond. The second is the callback function, which is executed when the fadeOut() function is fully executed $(‘.test’).fadeOut(1500,function(){})
slideUp() It just changes the height of the object, hides the height of the object from the bottom up,There are two parametersThe first can be a specified keyword,slow, normal, fast, or a specific millisecond. The second is the callback function, which is executed when slideUp() is fully executed $(‘.test’).slideUp(1500,function(){})
slideDown() Will only change the height of the object, display the height of the object from top to bottom,There are two parameters, the first can be the specified keyword,slow, normal, fast, or the specific millisecond. The second is the callback function, which is executed when the slideDown() function is fully executed $(‘.test’).slideDown(1500,function(){})
animate() Custom animationThis function is the most powerful. The above three pairs are used to change a single attribute, while this one can customize multiple attributes at the same time. Params: an object containing style attributes and values, such as height:’show’,opacity:’show’,speed :’show’}, optionally callback: The function that executes after the animation completes The ‘$(‘). The animate ({{height:’ show ‘, opacity: ‘show’}, 1500, the function () {}) / / the animate can holdRow summation or subtractionFor example
.stop() Stops the animation in progressEvery time JQ executes an animation, it will put the animation into a queue and execute it in turn. Most of the time, the animation is not finished, but the event and the end, for example: Mouse move out of the movie, when the mouse moved to trigger an animation, animation is not over yet, however, the mouse is moved out of the, at this time and until the end of the animation of the move can be performed out of animation, this clearly is not scientific, so can get through it. The stop () method, which will be performed off the end of the animation to implement new animation $(‘.test’).stop().animate({left:’300′},200)
is(‘:animated’) Determines whether the element is animated, when actual use, a lot of time to avoid the accumulation of animation, such as the case said the mouse move out, if remove the mouse back and forth many times in fast, the animation will accumulate, if don’t have to stop (), then you can judge whether the current element animation being executed, if the current element is executing the movie, so there is no need to add animation if(! $(element).is(‘:animated’)){// If no animation is executed, add a new animation}
toggle() Switching the visible state of an element is equivalent to combining hide() with show() $(‘.test’).toggle()
slideToggle() Switching the height state of an element is equivalent to combining slideUp() with slideDown() $(‘.test’).slideToggle()
fadeTo() This method toggles the opacity of an element to a specified state The ‘$(‘). FadeTo (600,0.2)

Add or subtract animation

// Each time you click on the.test element, it moves 500px further to the left
$('.test').on('click', () = > {$(this).animate({left:'+ = 500'},300)})// Each time you click on the.test element, its distance to the left decreases by 200px
$('.test').on('click', () = > {$(this).animate({left:'- = 200'},300)})Copy the code

JQuery to form, form operations

| the |. Focus () method actually and CSS selector: focus, but ie6 support in addition to hover in the selector, so you can use this to replace, the specific function is triggered when focusing function | $(” input “). The focus (the function () {}) |

Check boxes for all, uncheck, and none

/ / all
$('[name=item]:checkbox').attr('checked'.true)
/ / don't choose
$('[name=item]:checkbox').attr('checked'.false)
/ / the choice
$('[name=item]:checkbox').each((a)= >{$(this).attr('ckecked',! $(this).attr('ckecked'))})Copy the code

Contains the specified text content highlighting

// Implemented via the selector :contains
$('tr: contain (" detective ")').addClass('selected')
Copy the code

This section in the book is nothing special, just speak some form, they have been used for elements in the operation to the method, which is before the speaking of those, just a combination, so there is no new content, the actual form will form part of the behind only do an instance: the form in the pages of the plug-in or actual use;

JQuery and Ajax

load(url [,data] [,callback])

  • Url: the URL of the requested HTML page.
  • Data: Indicates the key/value sent to the server.
  • Callback: Optional callback function to execute after the request completes;

Usually used in the HTML page to load to the specified location, such as: background management page, according to the navigation button, on the right or right side of the specified page to load different content without refreshing the page

If the second data has no parameters, then the default GET mode is used. If there is a data, it will automatically change to POST mode **

// After clicking on the element of class BTN, the testHtml page is loaded in the element with id test
$('.btn').on('click'.function(){$('#test').load('testHtml.html')})/ / the GET method
$('#test').load('testHtml.html'.function(){})

/ / POST way
$('#test').load('testHtml.html', {name:'rain'.age:'22'},function(){})
Copy the code

$.get(url [,data] [,callback] [,type])

  • Url: the requested URL address;
  • Data: Optional. Key /value data sent to the server is appended to the requested URL as a QueryString.
  • Callback: Optional, the callback function automatically passes the request result and status to this method on successful loading (this method is called only if the return status of Response is SUCCESS);
  • Jq determines the content format, such as XML, HTML, script, JSON, text, and _default. This parameter is optional.
// After clicking on the element of class BTN, the testHtml page is loaded in the element with id test
$('.btn').on('click'.function(){
	$.get('Server address', {user: $('#userInput').val(),
    content: $('#content').val()
  },function(data,status){
  	//data, the data returned after the result is requested
    //status, the status returned by the request
    $('#div').html(data)
  })
})

Copy the code

$.post(url [,data] [,callback] [,type])

.get() is used in the same way as.get(). The only difference is that the method of submission is get and POST.

The difference between POST and GET:

  • GET requests send parameters to the server after the URL, while THE PARAMETERS of POST are passed in the BODY of the HTTP message. Comparatively speaking, the parameters of POST are better hidden, but if you are willing to do so, they are not reliable.
  • The GET mode has a limit on the size of data to be transferred, which cannot exceed 2KB. The POST mode has no limit in theory.
  • GET the requested data will be the browser cache, so others can read the data from the browser’s history, if the password is to use a GET request, then the account password will be cached, and POST request data will not be cached, this point to see if the data have a certain request for safety, so want to use a POST request;
// After clicking on the element of class BTN, the testHtml page is loaded in the element with id test
$('.btn').on('click'.function(){
	$.post('Server address', {user: $('#userInput').val(),
    content: $('#content').val()
  },function(data,status){
  	//data, the data returned after the result is requested
    //status, the status returned by the request
    $('#div').html(data)
  })
})
Copy the code

$.getScript(url,success(response,status))

Get and run a JavaScript file through an AJAX request

  • Url: indicates the URL address
  • Success: The callback function, which is run after the javaScript file has successfully loaded, takes two arguments, the first is the returned data and the second is the returned state
// Click on the element named BTN to load a test.js js file
$('.btn').on('click'.function(){
	$.getScript('xxx/test.js'.function(data,status){
  	//data, the data returned after the result is requested
    //status, the status returned by the request
    $('#div').html(data)
  })
})
Copy the code

$.getJSON(url,success(response,status))

The getJSON() method uses AJAX’s HTTP GET request to GET JSON data

  • Url: indicates the URL address
  • Data: Indicates the data to be sent
  • Success: The callback function, which is run after the javaScript file has successfully loaded, takes two arguments, the first is the returned data and the second is the returned state
// Click on the element named BTN to load a test.js js file
$('.btn').on('click'.function(){
	$.getJson('xxx/test.json'.function(data,status){
  	//data, the data returned after the result is requested})})Copy the code

$.ajax(option)

This is the lowest level Ajax method in JQ. All other methods are implemented using this method. Option has the following parameters:

parameter type instructions
url String The address of the server requesting the data
type String How to request data, POST or GET, default is GET
timeout Number Timeout of the request, in milliseconds
data The Object or a String The data sent to the server, which can be either an object or a string, needs to be negotiated with the backend developer
dataType String XML: XML document HTML: HTML information. If it is HTML that contains script, script will run script when inserting DOM: Json: JSON data jSONP: JSONP format Text: plain text string
beforeSend Function Sending request money can modify the XMLHttpRequest object’s functions, such as adding custom request headers
complete Function The callback function that is invoked after the request completes, whether the request succeeds or fails
success Function This function takes two parameters by default: the first: the data returned by the server and the second: the status string of the returned data
error Function This function takes three default arguments: first: XMLHttpRequest object second: error message third: optional, captured error object
global Boolean The default is true, which indicates whether the global Ajax time is triggered, as described in the next section
// After clicking on the element of class BTN, a request is sent
$('.btn').on('click'.function(){
	$.ajax({
  	type:'POST'.// Specify POST, otherwise default GET
    url:'test.js'.// Server address
    data:{	/ / data
    	name:'yzq'.content:'test'
    },
    success(data,status){
    	// Request success is the triggered function
    },
    error(xml,status,error){
    	// Request failures are triggered functions}})})Copy the code

Ajax global events in jQuery

Global events are events that are triggered whenever an Ajax request occurs on a page

methods describe The sample
.ajaxStart() Trigger when any Ajax request starts, such as when the request starts to trigger the loading animation within the load $(document).ajaxStart(function(){$(‘#loading’).show()})
.ajaxStop() Triggered when any Ajax request ends, such as when the loading box is hidden $(document).ajaxStart(function(){ $(‘#loading’).hide()})
.ajaxComplete() Triggered when any Ajax request completes, this is similar to ajaxStop() $(document).ajaxComplete(function(){$(‘#loading’).hide()})
.ajaxError() Execute when an error occurs in any Ajax request $(document).ajaxComplete(function(){alert(‘ error ‘)})
.ajaxSend() Any Ajax request must be executed before it is sent. Specifies the function to run when the request succeeds. Additional parameters: Event contains the event object XHR – contains the XMLHttpRequest object options – contains the options used in the AJAX request $(document).ajaxsend (function(e, XHR,opt){alert(‘ error ‘)})
.ajaxSuccess() A function that is executed when any Ajax request succeeds $(document).ajaxComplete(function(){alert(‘ request successful ‘)})

The use and writing of plug-ins

Plug-in, also called extension, is a program written in accordance with a certain standard application program interface;

Types of plug-ins

It can be roughly divided into three categories:

  • Parnet (), addClass(), DOM (), parnet(), parnet(), addClass(), etc.
  • Wrapper global functions: You can add separate functions to the jQuery namespace, such as the usual $.ajax() method and $.trim() method with whitespace removed.
  • Selector plugins: In some cases, you will need to use the selector plugins. JQuery’s selector plugins are very powerful, but they need to be extended.

The bottom line

  • JQuery plugin files are named jquery.custom name.js, for example, jq.color.js.
  • All object methods should be attached to jquery.fn objects, and all global functions should be attached to jQuery itself;
  • Inside the plugin, this points to the jQuery object currently retrieved through the selector, rather than the DOM element as usual.
  • You can iterate through all elements with this.each;
  • All method or function plug-ins should end with a semicolon (;); otherwise, they may have problems with compression.
  • The plugin should return a jQuery object to keep the plugin chained, unless the plugin needs to return something that needs to be retrieved, such as a string or array.
  • Avoid using $as a jQuery object alias inside your plug-in. Instead, use the full jQuery representation to avoid collisions. You can also use the reporting technique to get around this problem;

Template format

// Book recommendation; (function($){
	// Here is the plug-in code
  let foo;
  let bar = function(){}
  
  // Add the function to the $object
  $.BAR = bar;
})(jQuery)
Copy the code

Use an instant-execute function to separate the real plug-in code inside the function body, so that you don’t have to worry about variable contamination. Variables written inside the function body cannot be accessed externally.

Mechanism of plug-ins

JQuery provides two methods to extend the functionality of jQuery, jquery.fn.extend () and jquery.extend (), both of which accept an Object Object as an argument;

jQuery.fn.extend()

Use to extend the first of three types of plug-ins, such as the color() plug-in, which has two functions

  • Sets the color for the matched element
  • Gets the color of the first element in the matched element
; (function($){
	$.fn.extend({
  	color:function(value){
    	// Plug-in code
      // Check if there is a value, if there is a value, then it is set, if there is no value, then it is fetch
      if(! value){// This refers to the DOM element on which the method is currently called
      	return this.css('color');
      }
      else{
      	return this.css('color',value);
      }
    }
  })
})(jQuery)
Copy the code

jQuery.extend()

Used to extend the latter two plug-ins and have a very powerful function: extend existing Object objects;

// This method will merge obj1, obj2, and so on into the target object. If they have the same property name, the latter will overwrite the previous onejQuery.extend(target,obj1,obj2,... ,objN);Copy the code

Therefore, jquery.extend () is often used to set a series of default parameters for plug-in methods, such as:

//.test calls validata() and passes an object
$('.test').validate({
	name:'bar'.length:5
})
/ / the plugin; (function($){
  let DEFAULT_OPTION={
  	name:'BAR'
  }
	$.fn.extend({
  	validate:function(option){
      // If the user has passed the configuration, the configuration item in the configuration will override the default configuration. If not, the default configuration will be enabled
      let newOption = jQuery.extend(DEFAULT_OPTION,option) 	
  })
 })(jQuery);
Copy the code

If you need to extend an existing global method, you can do this

; (function($){
  $.extned({
  	ltrim:function(text){
    	return (text||' ').replace(/^\s+/g."");
    }
  })
 })(jQuery);

/ / call
jQuery.ltrim(' test ')
Copy the code

case

Create a lightweight form validation plugin that requires:

  • Can verify different types of input boxes, at least the following types of authentication: mobile phone number, ID number, email, mandatory;
  • Validation rules can be customized, if not, the default validation rules will be enabled;
; (function(root,func,plugIn){ func(jQuery,plugIn); }) (this.function(jQuery,plugIn){
    var DEFAULTS = {
        plugInName:"dv".initEvent:"input".initError:"The information you entered is wrong. Please check it carefully.".initRequired:"This input is required".// Function appeal
        rules:{
            "email":/^\w+@\w+\.\w+$/."mobile":/^1\d{10}$/."password":16th {8} $/ / ^ \ w."landline":/ ^ \ d {3, 4} - \ d {7, 8} $/
        }
    }
    
    $.fn[plugIn] = function (option) {
        var _this_ = this;
        // Check if the method is called by the form, and return it if not
        if(! _this_.is("form")) {return _this_;
        }
        // if form is used
        var NEW_DEFAULTS = objExtend(DEFAULTS,option);
        $.extend(_this_,NEW_DEFAULTS);
        _this_.$finds = _this_.find("input");
        _this_.$finds.on(_this_.initEvent,function(){
            var _this = $(this);
            _this.siblings('p').remove();
            // console.log(this);
            var $required = _this.data(_this_.plugInName+"-required");
            if(isBoolean($required) && isRequired.call(_this)){
                _this.after("

"

+_this_.initRequired+"</p>")}else{ $.each(_this_.rules,function(key,fn){ var $findName = _this.data(_this_.plugInName+"-"+key); var $error = _this.data(_this_.plugInName+"-"+key+"-error"); if($findName){ var result = testRegExp.call(_this,_this_.rules[key]) $error = $error || _this_.initError; if(! result){ _this.after("

"

+$error+"</p>")}}})// Merge specifications function objExtend(target,source){ if(! (isObj(target)&&isObj(source))){return this; } var targetKeys = Object.keys(target); targetKeys.forEach(function(index){ if(! isObj(target[index])){ target[index] = source[index]? source[index]:target[index]; }else{ target[index] = isObj(source[index])? copyTarget(target[index],source[index]):target[index]; }})return target; } /** * regular merge ** / function copyTarget(target,source){ if(! (isObj(target)&&isObj(source))){return this; } for(var i in source){ if(isRegExp(source[i])){ target[i] = source[i] } } return target; } /** * check for regular ** / function testRegExp(reg){ if(! isRegExp(reg)){return this; } return reg.test(this.val()); } /** * Mandatory test */ function isRequired(){ return this.val() === ' ' } function isObj(obj){ return Object.prototype.toString.call(obj) === "[object Object]"; } function isRegExp(reg){ return Object.prototype.toString.call(reg) === "[object RegExp]"; } function isBoolean(boolean){ return Object.prototype.toString.call(boolean) === "[object Boolean]"; }}},"validate") Copy the code

The appendix

JQuery performance optimization

  • ID selector > Tag selector > Class selector > Property selector
  • With cached objects, try not to fetch the DOM once without doing a DOM operation using the selectors. Of course, this is fine if you use chain operations, such as:
let dom = $('#id');
dom.css('color'.'# 333333');
dom.on('click'.function(){})
/ / or
dom.css('color'.'# 333333').on('click'.function(){})
Copy the code
  • When looping over the DOM, you can insert the DOM once after the loop ends, for example:
// For example, if you have an array of length 100, you need to insert each item as li into ul,
// It is best not to insert the DOM once without looping, 100 times

// We can iterate through the array, store the contents as strings, and then insert them into the DOM once
letlist = [...] ;let strLi = ' ';
for(let i = 0; i<list.length; i++){ strLi +='<li>'+list[i]+'</li>'
}
$('#id').html(strLi);
Copy the code
  • Instead of binding events to each element, use an event broker
$(table).on('click'.function(e){
	let target = $(e.target);
  / /...
})
Copy the code
  • For better reuse, try to package a feature as a plug-in

JQuery skills

  • Disable right click
$(function(){$(document).on('contextmenu'.function(e){
  	return false; })})Copy the code
  • Determines whether the element exists
// Check the presence by length
if($('#id').length){
  //do someing
}
Copy the code